Implement your own String replaceAll method. Write tests,
Solution in Java
importcom.citrix.mstest.Application;importorg.springframework.boot.test.SpringApplicationConfiguration;importorg.springframework.test.context.testng.AbstractTestNGSpringContextTests;importorg.testng.annotations.DataProvider;importorg.testng.annotations.Test;importstaticorg.testng.Assert.assertEquals;@SpringApplicationConfiguration(Application.class)publicclassSome1TestextendsAbstractTestNGSpringContextTests{@DataProviderpublicObject[][]replaceAllParameters(){returnnewObject[][]{{"hello Eric Erik","E","H","hello Hric Hrik"},{"hello Eric Erik","Eric","Erik","hello Erik Erik"},// oldStr is at the end{"hello Eric Erik","Erik","Eric","hello Eric Eric"},// oldStr is at the begining{"hello Eric Erik","hello","Hello","Hello Eric Erik"},// No oldStr in sourceStr{"hello Eric Erik","H","E","hello Eric Erik"},// Length of oldStr is more than length of sourceStr{"hello Eric Erik","hello Eric Erik!","Hello","hello Eric Erik"},// "" cases{"hello Eric Erik","","H","hello Eric Erik"},{"hello Eric Erik","","","hello Eric Erik"},{"hello Eric Erik","Eric","","hello Erik"},{"","Eric","Joe",""},// No changes if there is null{"hello Eric Erik",null,"Erik","hello Eric Erik"},{"hello Eric Erik","hello",null,"hello Eric Erik"},{null,"hello","bye",null},{null,null,null,null}};}@Test(dataProvider="replaceAllParameters")publicvoidreplaceAllTest(StringsourceStr,StringoldStr,StringnewStr,StringfinalStr){assertEquals(replaceAll(sourceStr,oldStr,newStr),finalStr,"Unexpected result: ");}publicStringreplaceAll(StringsourceStr,StringoldStr,StringnewStr){if(sourceStr==null||oldStr==null||newStr==null)returnsourceStr;if(oldStr.length()==0)returnsourceStr;if(sourceStr.length()<oldStr.length())returnsourceStr;Stringresult="";inti=0;while(i<sourceStr.length()){if(foundStr(sourceStr,i,oldStr)){result=result+newStr;i=i+oldStr.length();}else{result=result+sourceStr.charAt(i);i++;}}returnresult;}privatebooleanfoundStr(Stringsource,inti,Stringstr){if(source.length()-i-str.length()<0)returnfalse;for(intj=0;j<str.length();j++){if(str.charAt(j)!=source.charAt(i+j))returnfalse;}returntrue;}}