我正在开发一个程序,要求用户输入一个短语和一个整数。该整数用于标识将从短语中返回哪个单词。例如,如果他们输入 5,程序应向用户返回句子中的第五个单词。
System.out.println("Your word is: " +combineString(phrase,numWord));
这是我到目前为止的工作,有一个主要的输出,
public static String combineString(String newPhrase, int newNum) {
int countWords = 0;
String word = "";
//words count. I'll +1 everytime using countWord the match the amount of words
for(int i=0; i< newPhrase.length(); i++) {
if(newPhrase.charAt(i) == ' ') {
countWords++;
}
}
//return the last word. Ex: 15 words in a phrase if user pick the 18th word it will return the 15th word.
if(countWords+1 < newNum || countWords+1 <= newNum) {
word += newPhrase.substring(newPhrase.lastIndexOf(' ')+1, newPhrase.length()-1);
}
else if(newNum <=0) { //return null if the user pick 0 or less than 0
word += null;
}
return word;
我对如何处理中间部分思考了很多,我的想法是,如果用户选择 numWord = 5,那么为了返回该句子中的第五个单词,我需要使用“newPhrase.substring(space 4th +1, space 5th)”。这就是我陷入困境的地方,因为我不知道如何开始,也不知道如何到达第四空间。
最佳答案
public static String combineString(String newPhrase, int newNum) {
if(newNum<=0)
return null;
String word = "";
String [] match = new String[newNum];
int j =0;
for(int i=0; i< newPhrase.length(); i++) {
word = word + newPhrase.charAt(i);
if(newPhrase.charAt(i) == ' ') {
match[j] = word;
if(j+1 == newNum) {
return word; // returns the specified word
}
j++;
word = "";
}
}
return word; //returns last word
}
此代码应该适合您。如果是这样的话,请接受答案。
关于java - 不使用 .split() 或 StringTokenizer 在用户内容中查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58562961/