从字符串中提取每个单词

时间:2013-10-02 18:35:37

标签: java string

我正在尝试计算String中的单词数,找到String中每个单词的长度,然后仅使用String类确定String中的最大单词。我不能使用数组。有没有人知道从字符串中提取每个单词的方法?

5 个答案:

答案 0 :(得分:3)

int indexOfSpace = 0;
int nextIndexOfSpace = 0;

String sentence  = "This is a sentence";

int lastIndexOfSpace = sentence.lastIndexOf(" ");
while(indexOfSpace != lastIndexOfSpace){
    nextIndexOfSpace = sentence.indexOf(" ",indexOfSpace);  
    String word = sentence.subString(indexOfSpace,nextIndexOfSpace);
    System.out.println("Word: " + word + " Length: " + word.length());
    indexOfSpace = nextIndexOfSpace;
}

String lastWord = sentence.subString(lastIndexOfSpace);
System.out.println("Word: " + lastWord + " Length: " + lastWord.length());

你需要按照以上几点做点什么。由于您的问题似乎是一个家庭作业问题,我不打算为此进行调试。这是我可以回答看起来像家庭作业的问题。

调试它,使用它。

答案 1 :(得分:2)

Scanner s= new Scanner("Put your string here");
while(s.hasNext()){
    String word= s.next();
}

仅使用字符串进行编辑:

String myString = "hello world how are you";
for (int i = 0,                   //start of word
     j = 0;                       //end of word
     i < myString.length();       //make sure we're in bounds
     i = j + 1) {                 //Start from where we left off plus one
                                  //to get rid of space we just found

    j = myString.indexOf(" ", i); //find the next space
    if (j == -1) {                //-1 means no more spaces so we're done
        break;
    }
    String word = myString.substring(i, j); //here is your word
}

答案 2 :(得分:2)

使用StringTokenizer

String sentence = "This is a sentence"; 
StringTokenizer t = new StringTokenizer(sentence);
String word ="";
while(t.hasMoreTokens())
{
    word = t.nextToken();
    System.out.println(word);
}

输出应为

This
is
a
sentence

答案 3 :(得分:0)

这可以使用split(“”)//将字符串(可能是一个句子)用空格分成单词并使用数组列表来存储List words = Arrays.asList(sentence.split(“”)) ;

答案 4 :(得分:0)

原始版本,可能是高效的,可能是这样的。这假设在单词之间有单个空格,包括最后可以轻松调整使其完美。



    int wordCount = 0;
    int maxWordLen = 0;
    String longestWord = null;

    if(input != null){//given word
        int currentWordStart = 0;
        for(int i = 0; i < input.length(); i++){
            char currentChar = input.charAt(i);
            if(' ' == currentChar){
                wordCount++;
                String currentWord = input.substring(currentWordStart, i);
                int currentWordLen = i - currentWordStart;
                System.out.println("Word: " + currentWord + ", Length: " + currentWordLen);
                currentWordStart = i + 1;
                if(maxWordLen < currentWordLen){
                    maxWordLen = currentWordLen;
                    longestWord = currentWord;
                }
            }
        }
    }

    System.out.println("Word count: " + wordCount);
    System.out.println("Longest word: " + longestWord + ", Length: " + maxWordLen);