我正在試圖製作一個程序,爲每個第n個字,該字符串中的單詞被顛倒。然而,我已經對循環中的變量發生了很多混淆,因爲不是顛倒這個單詞,而是讓整個事物變成空白。這是我的代碼,它只是主程序反轉過程的返回方法;字符串與每個循環得到更新的字符不連接
public static String reverse(String s, int n) {
String[] parts = s.split(" "); //separating each word of the string into parts of an array
String finalS = ""; //this will be the new string that is printed with all the words reversed\
char a;
for (int i = 0; i < parts.length; i++) {
int wordCount = i + 1; //making it so that it's never 0 so it can't enter the if gate if just any number is entered
if (wordCount%n==0) { //it's divisible by n, therefore, we can reverse
String newWord = parts[i]; //this word we've come across is the word we're dealing with, let's make a new string variable for it
for (int i2 = newWord.length(); i2==-1; i2--){
a = newWord.charAt(i2);
finalS += a;
}
}
else {
finalS += parts[i]; //if it's a normal word, just gets added to the string
}
if (i!=parts.length) {
finalS += " ";
} //if it's not the last part of the string, it adds a space after the word
}
return finalS;
}
比第n個其他的每一個字返回完美的,沒有變化,但第n詞只是有空格。我覺得這是由於變量之間沒有互相交流和循環。任何幫助,將不勝感激。謝謝。
非常感謝您的完美! – petegoast