ashG ashG -5 years ago 93
Java Question

How to replace a repeating char at only a particular place in String?

I have a string like : Hi/I/Jack/there

which contains multiple '/' between values. And these values are not of fixed length(can be any length)

And I need to replace only second occurrence of '/' with another string that means the Output should be..

How should I achieve this? tried with String.replace and some logic but it's replacing all occurrences where as I need only 2nd occurrence to replace. And I'm restricted to use String only(not StringBuilder or something else)

Answer Source

Count / by each element in String

    String s = "Hi/I/Jack/there";

    for(int i=0,count=0;i<s.length();i++)
        if(s.charAt(i)=='/')// if the i'th element is '/'
            if(count==2)//it's second '/'
                //separate to two part by second '/' and add what you want at middle
                s = s.substring(0,i) + "am" +s.substring(i+1,s.length());                    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download