我正在尝试计算字符串中的单词数,找到字符串中每个单词的长度,然后仅使用 String 类确定字符串中的最大单词。我不能使用数组。有谁知道从字符串中提取每个单词的方法?
问问题
27122 次
5 回答
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());
您需要按照上述思路做一些事情。由于您的问题似乎是一个家庭作业问题,因此我不会努力调试它。这是我所能回答的似乎是一个家庭作业的问题。
调试它,使用它。
于 2013-10-02T18:45:18.970 回答
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
}
于 2013-10-02T18:38:03.033 回答
2
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
于 2013-10-02T18:38:49.007 回答
0
这可以使用 split(" ")//将字符串(可能是一个句子)按空格拆分为单词并使用数组列表来存储 List words = Arrays.asList(sentence.split(" "));
于 2013-10-02T18:39:25.190 回答
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);
于 2013-10-02T19:12:27.217 回答