[SalesForce] How to insert a string into another string

I am having a string String S1="https://www.microsoft.com/s/5f5wpyvu1cbdek2ld3as"

I am having another string String S2="0000000/demowidget".

I want to insert my new string S2 into my old string S1 just before "/s"

any help?

Best Answer

Lets say you have the following strings.

String1 = 'myString/myPattern/someString'
String2 = 'newString'

You can append your new string just before the required pattern like this.

String newString = 
    String1.substring(0, String1.indexOf('/myPattern')) +
    String2 + 
    String1.substring(String1.indexOf('/myPattern'), String1.length());

But make sure your pattern is not repeated in the String1, because you might end up replacing just the first occurrence.

Related Topic