Home > Net >  Is it possible to replace all occurrences of a char in a string, but differently on first and last o
Is it possible to replace all occurrences of a char in a string, but differently on first and last o

Time:07-29

I want to replace all occurrences of backslash char in my string to " char. But in one condition, for the first and last occurrences of backslash, I want it to be replaced differently for first and last occurrences.

String as example:

 id_123,balance_account,\openDate\:\600\

Should be changed to:

 id_123,balance_account,{"openDate":"600"}

As you can see, I want to replace the first and last appearance of the backslash in the string, to the new pattern, which consists of 2 chars: In first occurrence: {" In last occurrence: "}

CodePudding user response:

it is actually easy! :

you need to use indexOf('/',0) for the first occurence.

you can use lastIndexOf('/') for the last occurence.


int firstInde = myString.indexOf('/');
// do your swap here
int lastIndex - myString.lastIndexOf('/');
// do your other swap here
if (firstIndex == lastIndex || firstIndex =-1 || lastIndex = -1)
   return
int index = myString.indexOf('/', firstIndex);
while(index<lastIndex) {
   // do your swap
   index =  myString.indexOf('/', index);
}

CodePudding user response:

String input = "id_123,balance_account,\\openDate\\:\\600\\";
Pattern p = Pattern.compile("\\\\");
Matcher m = p.matcher(input);
StringBuilder sb = new StringBuilder();
if (m.find()) {
    m.appendReplacement(sb, "{\"");
    while (m.find()) {
        m.appendReplacement(sb, "\"");
    }
    sb.append("}");
    m.appendTail(sb);
}
  • Related