Search code examples
java

Add ' to particular place in String in Java


I have string like following.

"pqrs, ABC Inv, ABC Inv; Inc. (us), AAC Inv pqr, abcd"

I want to add ' before and after the string which have ; separated by ,. Means, I want ' before and after this string in above example ABC Inv; Inc. (us).
And also wants to remove ; from that string.

So, my final result would be.

"pqrs, ABC Inv, 'ABC Inv Inc. (us)', AAC Inv pqr, abcd"

I tried following:

public static void main(String []args){
     String s = "pqrs, ABC Inv, ABC Inv; Inc. (us), AAC Inv pqr, abcd";
     
     String[] split = s.split(";");
     String firstStr = split[0];
     String secondStr = split[1];

    int index = firstStr.lastIndexOf(',');
    int index1 = secondStr.indexOf(',');

    
    String newstr =  s.substring(0, index+1) + "'" + s.substring(index+1, index+index1+1) + "'" + s.substring(index+index1+1) ;
    System.out.println(newstr.replaceAll(";", ""));

 }

But, not working properly. It give me result like:

pqrs, ABC Inv,' ABC Inv 'Inc. (us), AAC Inv pqr, abcd

Any help would be greatly appreciated.


Solution

  • Something closer to your original:

    String newstr =  firstStr.substring(0, index+2) + "'" + firstStr.substring(index+2) + secondStr.substring(0, index1) + "'" + secondStr.substring(index1) ;
    System.out.println(newstr);
    

    Even closer:

    String newstr =  s.substring(0, index+1) + "'" + s.substring(index+1, firstStr.length()+index1+1) + "'" + s.substring(firstStr.length()+index1+1) ;