0

Replacing word of a string using java

String s1="Im working in google,google is in Bangalore String s2= "Microsoft" How can we replace second occurrence of google from s1 by s2 using java?

16th Feb 2020, 3:40 PM
niranjan
4 Réponses
+ 4
You can use replaceFirst() method of Java equivalent to replace(str, 1) of python and ruby's sub(). It only replace the first occurrence of string. If you use replaceFirst() than output will be "I'm working in Microsoft,Google......" not "I'm working in Microsoft, Microsoft....". However this is not what you want but you can manage it by doing some boilerplate stuff.
16th Feb 2020, 5:10 PM
0_O-[Mägár_Sám_Äkà_Nüllpøïntêr_Èxëcéptïön]~~
0_O-[Mägár_Sám_Äkà_Nüllpøïntêr_Èxëcéptïön]~~ - avatar
+ 3
First tell on which language you are talking? In Java you can use replace method. https://www.javatpoint.com/java-string-replace
16th Feb 2020, 3:45 PM
A͢J
A͢J - avatar
0
But I need to replace only second occurrence of the word google,if we use replace method it may replace both the occurrences of the word google.
16th Feb 2020, 3:50 PM
niranjan
0
Use index Of method to find first occurrence of word, then search from next word. Then use replace method. For your example, index Of method returns 14, then staring from +1= 15(infact need +length of goolge) will replace 2nd occurece of s2. Edit: Got it?
16th Feb 2020, 4:10 PM
Jayakrishna 🇮🇳