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?
4 Answers
+ 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.
+ 3
First tell on which language you are talking?
In Java you can use replace method.
https://www.javatpoint.com/java-string-replace
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.
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?