只迭代和使用数组来跟踪词的一个非常简单的方法...
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