根据原始帖子的修改,OP现在指示其目标是颠倒句子中单词的字母顺序,但将单词保留在其初始位置。
我认为,最简单的方法是利用String
split函数,遍历单词并颠倒其顺序。
String[] words = sentence.split(" "); // splits on the space between wordsfor (int i = 0; i < words.length; i++) { String word = words[i]; System.out.print(reverseWord(word)); if (i < words.length-1) { System.out.print(" "); // space after all words but the last }}
该方法
reverseWord定义为:
public String reverseWord(String word) { for( int i = 0; i < word.length(); i++) { stk.push(word.charAt(i)); } return stk.empty();}
并将
empty方法更改为:
public String empty() { String stackWord = ""; while (this.first != null) stackWord += this.pop(); return stackWord;}
原始回应
最初的问题表明,OP希望完全推翻这句话。
您有一个真正不需要的双循环构造。
考虑以下逻辑:
- 从输入字符串中读取每个字符并将该字符推入堆栈
- 当输入字符串为空时,从堆栈中d出每个字符并将其打印到屏幕上。
所以:
for( int i = 0; i < sentence.length(); i++) { stk.push(sentence.charAt(i));}stk.empty();
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)