简体   繁体   English

是否可以替换字符串中所有出现的字符,但在第一次和最后一次出现时不同?

[英]Is it possible to replace all occurrences of a char in a string, but differently on first and last occurrences?

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: "}如您所见,我想将字符串中反斜杠的第一次和最后一次出现替换为由 2 个字符组成的新模式:第一次出现:{“最后一次出现:”}

it is actually easy:其实很简单:

you need to use indexOf('/',0) for the first occurence.您需要在第一次出现时使用 indexOf('/',0) 。

you can use lastIndexOf('/') for the last occurence.您可以使用 lastIndexOf('/') 最后一次出现。


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);
}
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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM