0

此代码在main函数内部:

Scanner input = new Scanner(System.in);

System.out.println("Type a sentence");
String sentence = input.next();

Stack<Character> stk = new Stack<Character>();
int i = 0;

while (i < sentence.length())
{
    while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
    {
        stk.push(sentence.charAt(i));
        i++;
    }
    stk.empty();
    i++;
}

这是empty()功能:

public void empty()
{
    while (this.first != null)
        System.out.print(this.pop());
}

它不能正常工作,因为通过输入example sentence我得到这个输出:lpmaxe。第一个字母丢失,循环停止,而不是从空格算到句子的下一部分。

我正在努力实现这一目标:

This is a sentence---> sihT si a ecnetnes

4

6 回答 6

3

根据对原始帖子的修改,OP 现在表明他的目标是反转句子中单词的字母顺序,但将单词留在初始位置。

我认为,最简单的方法是使用 Stringsplit函数,遍历单词并颠倒它们的顺序。

String[] words = sentence.split(" "); // splits on the space between words

for (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想要完全颠倒这句话。

你有一个双循环结构,你并不真正需要它。

考虑这个逻辑:

  1. 从输入字符串中读取每个字符并将该字符压入堆栈
  2. 当输入字符串为空时,从堆栈中弹出每个字符并将其打印到屏幕上。

所以:

for( int i = 0; i < sentence.length(); i++) {
    stk.push(sentence.charAt(i));
}
stk.empty();
于 2012-07-18T15:40:20.060 回答
1

我假设您希望您的代码做的是依次反转每个单词,而不是整个字符串。因此,给定example sentence您希望它输出的输入elpmaxe ecnetnes not ecnetnes elpmaxe

您看到lpmaxe而不是的原因elpmaxe是因为您的内部while循环不处理字符串的最后一个字符,因为您有i < sentence.length() - 1而不是i < sentence.length()。您只看到一个单词的原因是您的sentence变量仅包含输入的第一个标记。这就是该方法的Scanner.next()作用;它读取下一个(默认情况下)以空格分隔的标记。

如果你想输入一个完整的句子,总结System.in如下:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

并打电话reader.readLine()

希望这可以帮助。

于 2012-07-18T15:46:37.610 回答
0

假设您已经输入sentence并调用了 Stack 对象stk,这是一个想法:

char[] tokens = sentence.toCharArray();
for (char c : tokens) {
    if (c == ' ') {
        stk.empty();
        System.out.print(c);
    } else  {
        stk.add(c);
    }
}

因此,它将一次扫描一个字符。如果我们击中一个空格字符,我们会假设我们已经击中了一个单词的结尾,反向吐出那个单词,打印那个空格字符,然后继续。否则,我们会将字符添加到堆栈中并继续构建当前单词。(如果您还想允许使用句号、逗号等标点符号,请更改if (c == ' ') {为类似等if (c == ' ' || c == '.' || c == ',') {。)

至于为什么你只得到一个字,darrenp 已经指出了。(就个人而言,除非速度是问题,否则我会使用 Scanner 而不是 BufferedReader,但这只是我的意见。)

于 2012-07-19T02:03:08.587 回答
0
import java.util.StringTokenizer;
public class stringWork {
public static void main(String[] args) {
    String s1 = "Hello World";
    s1 = reverseSentence(s1);
    System.out.println(s1);
    s1 = reverseWord(s1);
    System.out.println(s1);
}
private static String reverseSentence(String s1){
    String s2 = "";
    for(int i=s1.length()-1;i>=0;i--){
        s2 += s1.charAt(i);
    }
    return s2;
}
private static String reverseWord(String s1){
    String s2 = "";
    StringTokenizer st = new StringTokenizer(s1);
    while (st.hasMoreTokens()) {
        s2 += reverseSentence(st.nextToken());
        s2 += " ";
    }
    return s2;
}

}

于 2012-12-25T00:08:03.273 回答
0

公共类 ReverseofeachWordinaSentance {

/**
 * @param args
 */
public static void main(String[] args) {
    String source = "Welcome to the word reversing program";

    for (String str : source.split(" ")) {
        System.out.print(new StringBuilder(str).reverse().toString());
        System.out.print(" ");
    }
System.out.println("");

    System.out.println("------------------------------------ ");
    String original = "Welcome to the word reversing program";
    wordReverse(original);
    System.out.println("Orginal Sentence :::: "+original);
    System.out.println("Reverse Sentence :::: "+wordReverse(original));
}

public static String wordReverse(String original){

    StringTokenizer string = new StringTokenizer(original);

    Stack<Character> charStack = new Stack<Character>();

    while (string.hasMoreTokens()){

    String temp = string.nextToken();

    for (int i = 0; i < temp.length(); i ++){

    charStack.push(temp.charAt(i));
}
    charStack.push(' ');
}

    StringBuilder result = new StringBuilder();
    while(!charStack.empty()){
    result.append(charStack.pop());
}

    return result.toString();   
}

}

于 2013-10-24T06:53:56.780 回答
0
public class reverseStr {
public static void main(String[] args) {
    String testsa[] = { "", " ", "       ", "a ", " a", " aa bd  cs " };
    for (String tests : testsa) {
        System.out.println(tests + "|" + reverseWords2(tests) + "|");
    }
}

public static String reverseWords2(String s) {
    String[] sa;
    String out = "";
    sa = s.split(" ");
    for (int i = 0; i < sa.length; i++) {
        String word = sa[sa.length - 1 - i];
        // exclude "" in splited array
        if (!word.equals("")) {
            //add space between two words
            out += word + " ";
        }
    }
    //exclude the last space and return when string is void
    int n = out.length();
    if (n > 0) {
        return out.substring(0, out.length() - 1);
    } else {
        return "";
    }
}

}

这可以传入leetcode

于 2014-04-18T15:22:30.537 回答