如何用空格分隔单词?

时间:2015-11-24 15:18:10

标签: java string

我在这段代码中尝试做的是将五个单词输入中的每个单词分成它所构成的五个单词。我设法使用indexOf和substring将第一个单词与输入的其余部分分开,但是我在分离其余单词时遇到了问题。我只是想知道我能做些什么来解决这个问题。

import java.util.Scanner;

public class CryptographyLab {
    public static void main (String [] args) {
        fiveWords();
    }

    public static void fiveWords () {
        Scanner input = new Scanner(System.in);

        for (int i = 1; i <= 3; i++) {
            if (i > 1) {
                String clear = input.nextLine(); 
                // I was having some problems with the input buffer not clearing, and I know this is a funky way to clear it but my skills are pretty limited wher I am right now 
            }

            System.out.print("Enter five words: ");
            String fW = input.nextLine();
            System.out.println();
            // What I'm trying to do here is separate a Scanner input into each word, by finding the index of the space. 

            int sF = fW.indexOf(" ");
            String fS = fW.substring(0, sF);

            System.out.println(fS);

            int dF = fW.indexOf(" ");
            String fD = fW.substring(sF, dF);

            System.out.println(fD);

            int gF = fW.indexOf(" ");
            String fG = fW.substring(dF, gF);

            //I stopped putting println commands here because it wasn't working.
            int hF = fW.indexOf(" ");
            String fH = fW.substring(gF, hF);

            int jF = fW.indexOf(" ");
            String fJ = fW.substring(hF, jF);

            System.out.print("Enter five integers: ");
            int fI = input.nextInt();
            int f2 = input.nextInt();
            int f3 = input.nextInt();
            int f4 = input.nextInt();
            int f5 = input.nextInt();
            //this part is unimportant because I haven't worked out the rest yet

            System.out.println();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

返回下一个&#34;令牌的Scanner class has a next() method&#34;从输入。在这种情况下,我认为连续五次调用next()应该返回5个单词。

正如Alex Yan在答案中指出的那样,你也可以在字符串上使用split方法拆分某个分隔符(在本例中为空格)。

答案 1 :(得分:0)

您未正确提取字符串。但是还有另一个更简单的解决方案,我将在之后解释。

您的方法存在的问题是您没有正确提供索引。

第一轮提取后:

fW = "this should be five words"
sf = indexOf(" ") = 4
fS = fW.substring(0, sF) = "this"

这似乎是正确的。但在第二轮之后:

fW = "this should be five words". Nothing changed
df = indexOf(" ") = 4. Same as above
fD = fW.substring(sF, dF) = substring(4, 4). You get a null string

我们发现问题是因为indexOf()找到了第一次出现的提供的子字符串。 substring()不会删除您子串的部分。如果你想继续这样做,你应该删掉你刚刚收到的词。

space = input.indexOf(" ");
firstWord = input.substring(0, space);
input = input.substring(space).trim(); // sets input to "should be five words" so that indexOf() looks for the next space during the next round

一个简单的解决方案就是使用String.split()将其拆分为一个子串数组。

String[] words = fw.split(" ");

如果输入是&#34;这应该是五个单词&#34;

for (int i = 0; i < words.length; ++i)
    System.out.println(words[i]);

应打印:

this
should
be
five
words