给定一个特定字符串和出现在该字符串中的特定单词,我如何计算该单词之前的单词数量?
例如,给定句子“我住在农场的红房子里”和单词" red ",我如何确定该单词之前有多少个单词?我想创建一个以原始字符串和目标单词为参数的函数,并输出如下语句:
“
”
前面有4个单词
发布于 2019-04-16 02:13:14
只需找到指定单词的索引并使用substring
方法即可。然后将该子字符串按空格拆分,得到单词数组:
String str = "I live in a red house on the farm";
int count = str.substring(0, str.indexOf("red")).split(" ").length; // 4
发布于 2019-04-16 02:10:32
通常,您可以通过查找、搜索或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);
}
}
https://stackoverflow.com/questions/55694979
复制相似问题