java - 不使用 .split() 或 StringTokenizer 在用户内容中查找单词

标签 java if-statement java.util.scanner counter static-methods

我正在开发一个程序,要求用户输入一个短语和一个整数。该整数用于标识将从短语中返回哪个单词。例如,如果他们输入 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/

相关文章:

if-statement - 在 Swift 中的 if 语句中使用多个 let-as

java - Java 中的动态数组?使用 ArrayList 与 int[] array = new int[n]

java - 为什么 Log4J (jul) 尝试对来自供应商的字符串消息进行 MessageFormat

java 。在 JPanel 上调整大小问题

python - 将 random.choice 与 if/elif/else 语句一起使用

linux - 如何比较两个文件名的一部分并使用 'cat' 将它们附加在一起

java - JOptionPane 和 Scanner 输入问题

java - 如何在 Java 中有效比较用户输入和多个输出场景

java - 无法修复空指针异常

java - 如何让 java 在将输入分配给变量之前等待输入以避免 java.util.NoSuchElementException