【问题标题】:How to get word count for the part of a String preceding a specific word? [closed]如何获取特定单词之前的字符串部分的字数? [关闭]
【发布时间】:2019-04-15 18:07:14
【问题描述】:

给定一个特定的字符串和出现在该字符串中的特定单词,我如何计算该单词之前的单词数?

例如,给定句子“I live in a red house on the farm”和“red”这个词,我如何确定这个词之前有多少个词?我想创建一个函数,它将原始字符串和目标单词作为参数并打印如下语句:

“红”字前有4个字

【问题讨论】:

  • 试试这个:String str = "I live in a red house on the farm"; String[] array = str.split(" "); int i = 0; for(String x:array){ if (!x.equals("red")){ i++; }else{ break; } } System.out.println("There are " + i + " words before red"); } }
  • 理想情况下,这应该由自然语言处理库来处理。

标签: java string position


【解决方案1】:

只要找到指定单词的索引,使用substring方法即可。然后将该子字符串按空格拆分以获取单词数组:

 String str = "I live in a red house on the farm";
 int count = str.substring(0, str.indexOf("red")).split(" ").length;  // 4

【讨论】:

    【解决方案2】:

    通常你可以通过 find、search 或 indexOf 函数来做到这一点:

    试试看: https://www.geeksforgeeks.org/searching-for-character-and-substring-in-a-string/

    // Java program to illustrate to find a character 
    // in the string. 
    import java.io.*; 
    
    class GFG 
    { 
      public static void main (String[] args) 
      { 
        // This is a string in which a character 
        // to be searched. 
        String str = "GeeksforGeeks is a computer science portal"; 
    
        // Returns index of first occurrence of character. 
        int firstIndex = str.indexOf('s'); 
        System.out.println("First occurrence of char 's'" + 
                           " is found at : " + firstIndex); 
    
        // Returns index of last occurrence specified character. 
        int lastIndex = str.lastIndexOf('s'); 
        System.out.println("Last occurrence of char 's' is" + 
                           " found at : " + lastIndex); 
    
        // Index of the first occurrence of specified char 
        // after the specified index if found. 
        int first_in = str.indexOf('s', 10); 
        System.out.println("First occurrence of char 's'" + 
                           " after index 10 : " + first_in); 
    
        int last_in = str.lastIndexOf('s', 20); 
        System.out.println("Last occurrence of char 's'" + 
                         " after index 20 is : " + last_in); 
    
        // gives ASCII value of character at location 20 
        int char_at = str.charAt(20); 
        System.out.println("Character at location 20: " + 
                                                 char_at); 
    
        // throws StringIndexOutOfBoundsException 
        // char_at = str.charAt(50); 
      } 
    } 
    

    【讨论】:

    • 我试过了,但我试图找到关键字之前的实际字数,而不是索引。
    猜你喜欢
    • 2022-08-02
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多