给定一个特定的字符串和该字符串中出现的特定单词,如何计算该单词之前的单词数?
例如,鉴于句子“我住在农场的红房子里”和“红色”这个词,我怎么能确定这个词前面有多少个单词呢?我想创建一个函数,将原始String和目标字作为参数,并打印如下语句:
在“red”之前有4个单词
只需找到指定单词的索引并使用substring
方法。然后按空格分割该子字符串以获取单词数组:
String str = "I live in a red house on the farm";
int count = str.substring(0, str.indexOf("red")).split(" ").length; // 4
通常你可以通过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);
}
}