例如
> HW2.nthWord(3, "zero one two three four five six seven")
"zero three six"
下面是我写的代码,但它没有用。我不知道该怎么做。
public static String nthWord(int number, String s4){
int word = 0;
StringBuilder builder4 = new StringBuilder();
for(int i = 0; word <= number; i++){
if(s4.charAt(i) != ' '){
builder4.append(s4.charAt(i));
}else if(s4.charAt(i) == ' '){
word = word + 1;
}if (word == number){
builder4.append(s4.charAt(i));
}
}
return builder4.toString();
}
答案 0 :(得分:0)
试试这个
public static String nthWord(int number, String s4) {
StringBuilder builder4 = new StringBuilder();
String[] ss = s4.split(" ");
for (int i = 0; i * number <= ss.length; i++)
builder4.append(ss[i * number]).append(" ");
return builder4.toString().trim();
}