簡體   English   中英

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

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

我想將字符串中所有出現的反斜杠字符替換為“字符。但在一種情況下,對於第一次和最后一次出現的反斜杠,我希望它在第一次和最后一次出現時被不同地替換。

字符串為例:

 id_123,balance_account,\openDate\:\600\

應改為:

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

如您所見,我想將字符串中反斜杠的第一次和最后一次出現替換為由 2 個字符組成的新模式:第一次出現:{“最后一次出現:”}

其實很簡單:

您需要在第一次出現時使用 indexOf('/',0) 。

您可以使用 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