2016-11-25 190 views
2

對不起,對於長名稱,但我在這裏作爲初學者不知所措......可能我找不到現有的解決方案,因爲我沒有知道要搜索的術語。用包含原始子字符串的條件子字符串替換多個出現的子字符串

我想要做的是用一些包含原始子字符串的條件子字符串替換字符串中的所有子字符串。一個例子可能更加清楚:

String answerIN = "Hello, it is me. It is me myself and I." 
//should become something like: 
String answerOUT = "Hello, it is <sync:0> me. It is <sync:1> me myself and I" 

所以子字符串「我」應該由自己加上一些有條件的東西。我到目前爲止所嘗試的不起作用,因爲我一直在替換替換的子字符串。所以我結束了:

String answerOUT = "Hello, it is <sync:0> <sync:1> me. It is <sync:0> <sync:1> me myself and I" 

我的代碼:

 String answerIN = "Hello, it is me. It is me myself and I."; 
     String keyword = "me"; 
     int nrKeywords = 2; //I count this in the program but that's not the issue here 

     if (nrKeywords != 0){ 
      for (int i = 0; i < nrKeywords; i++){ 
       action = " <sync" + i + "> " + keyword; 
       answerIN = answerIN.replace(keyword, action); 
       System.out.println("New answer: " + answerIN); 
      } 
     } 

我無法弄清楚如何不能替代已經替換字符串的子部分。

回答

1

String#replace將會將您正在尋找的所有String替換爲您想要替換的東西。所以這是不可能與常規String#replace,因爲沒有「只能從這裏到那裏」。

你可以爲了與String的子方法的工作,以取代每種情況:

String input = "Hello, it is me. It is me myself and I."; 
String output = ""; 
String keyword = "me"; 
int nextIndex = input.indexOf(keyword), oldIndex = 0, counter = 0; 

while(nextIndex != -1) { 
    output += input.substring(oldIndex, nextIndex-1) + " <sync:" + counter + "> "; 
    oldIndex = nextIndex; 
    nextIndex = input.indexOf(keyword, nextIndex+1); 
    ++counter; 
} 
output += input.substring(oldIndex); 
System.out.println(output); 

O/P

Hello, it is <sync:0> me. It is <sync:1> me myself and I. 
相關問題