我正在制作聊天机器人,并且需要能够在找到关键字之前计算用户输入中的单词数。
我已经能够计算字符串中的单词总数,但不能算出单词之前的单词。
用户输入“count”,激活wordcount方法。系统会提示他们输入一个句子,然后在句子中输入要查找的关键字。程序输出关键字在句子中的单词(例如,这是第3个单词)。
我试过一个for循环遍历字符并找到空格,for循环中的if不会激活:
for(int i = psn - 1; i> = 0; i--)
if(phrase.charAt(i)==''){// if1
spaces = spaces + 1;
private int findKeyword(String statement, String goal, int startPos) {
String phrase = statement.trim().toLowerCase();
goal = goal.toLowerCase();
int psn = phrase.indexOf(goal, startPos);
while (psn >= 0) {
// Find the string of length 1 before and after
// the word
String before = " ", after = " ";
if (psn > 0) {
before = phrase.substring(psn - 1, psn);
// System.out.println("If 1 at "+psn);
}
if (psn + goal.length() < phrase.length()) {
after = phrase.substring(psn + goal.length(),
psn + goal.length() + 1);
System.out.println("If 2 at " + psn);
}
// If before and after aren't letters, we've
// found the word
if (((before.compareTo("a") < 0) ||
(before.compareTo("z") > 0)) // before is not a
//
&& ((after.compareTo("a") < 0) ||
(after.compareTo("z") > 0))) {
System.out.println("If 3 at " + psn);
return psn;
}
//
// The last position didn't work, so let's find
// the next, if there is one.
psn = phrase.indexOf(goal, psn + 1);
}
return -1;
}
我正在制作聊天机器人,并且需要能够在找到关键字之前计算用户输入中的单词数。
我已经能够计算字符串中的单词总数,但不能算出单词之前的单词。
(例如,你的单词是句子中的第3个单词)
使用String.split()
可以更轻松地实现您想要的功能。例如:
String[] words = statement.split(" "); // array of words that are separated by a space
for (int i = 0; i < words.length; i++){
if (words[i].equals(goal))
System.out.println("word found in "+i+" words);
}
更好的方法可能是简单地用空格字符拆分句子字符串,然后在结果列表中获取关键字的索引。
例:
String[] split = sentence.split(" ");
int numberOfWordsBeforeKeyword = Arrays.asList(split).indexOf(keyword);