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