言葉だけを追跡するために、配列を反復して使用すると非常に簡単なアプローチ...
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