只迭代和使用數組來跟蹤詞的一個非常簡單的方法...
import java.util.Arrays;
public class WordSplit {
public static void main(String[] args){
printStrings("This is a test string", 2);
}
public static void printStrings(String sentence, int skip){
String[] splitSentence = sentence.split(" ");
String[] afterSplit = Arrays.copyOfRange(splitSentence, skip, splitSentence.length);
int c = 0;
for(int i=0; i<skip; i++){
System.out.println(ordinal(i+1)+" word: "+splitSentence[i]);
}
System.out.print("The rest of the sentence: ");
for(String s: afterSplit){
System.out.print(s+" ");
}
System.out.println();
}
public static String ordinal(int i) {
String[] sufixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
switch (i % 100) {
case 11:
case 12:
case 13:
return i + "th";
default:
return i + sufixes[i % 10];
}
}
}
輸出:
1st word: This
2nd word: is
The rest of the sentence: a test string
要拆分串入詞,你可以使用'string.split(「」)'然後遍歷結果數組。 – Beethoven
http://stackoverflow.com/questions/7577543/how-to-replace-a-word-in-a-string –
OP有什麼作用。他們需要做的是爲這個單詞添加一個循環和一個臨時變量,而不是試圖在原地建立字符串。 – markspace