首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何获取字符串中位于特定单词之前的部分的字数?

如何获取字符串中位于特定单词之前的部分的字数?
EN

Stack Overflow用户
提问于 2019-04-16 02:07:15
回答 2查看 127关注 0票数 -3

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

例如,给定句子“我住在农场的红房子里”和单词" red ",我如何确定该单词之前有多少个单词?我想创建一个以原始字符串和目标单词为参数的函数,并输出如下语句:

前面有4个单词

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-16 02:13:14

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

代码语言:javascript
复制
 String str = "I live in a red house on the farm";
 int count = str.substring(0, str.indexOf("red")).split(" ").length;  // 4
票数 0
EN

Stack Overflow用户

发布于 2019-04-16 02:10:32

通常,您可以通过查找、搜索或indexOf函数来执行此操作:

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

代码语言:javascript
复制
// 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); 
  } 
} 
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55694979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档