Java 我需要从使用它的word中获取特定的word';s位置
我有这样的绳子Java 我需要从使用它的word中获取特定的word';s位置,java,string,Java,String,我有这样的绳子 Hello World!. Hey There 这里“world”在第二位,“There”在第五位,我如何在java中的特定位置得到这个词 根据空格拆分字符串,它将返回字符串数组。现在我们可以通过(position-1) 你好,世界!。嘿 你好 世界 哎 那里 p.S.我不认为你对待作为一个单独的单词 String str = "Hello World!. Hey There"; String[] parts = str.split("\\W+"); String second
Hello World!. Hey There
这里“world”在第二位,“There”在第五位,我如何在java中的特定位置得到这个词 根据空格拆分字符串,它将返回字符串数组。现在我们可以通过
(position-1)
你好,世界!。嘿
代码>作为一个单独的单词
String str = "Hello World!. Hey There";
String[] parts = str.split("\\W+");
String secondWord = parts[1];
一定要使用正则表达式来检测分词符。在我的示例中,这是\W+
,它是一个或多个非单词字符
/*@input:是要搜索的源字符串*
/*@input: is the source string to search*
* @word is the key to search
* @returns the position of the word if prsent else -1 is returned
*/
public static int wordPosition(String input,String word)
{
String[] result=input.split(" ");
for(int i=0;i<result.length;i++)
{ if(result[i].contains(word))
return i+1;
}
return -1;
}
*@word是搜索的关键
*@如果返回prsent else-1,则返回单词的位置
*/
公共静态int字位置(字符串输入,字符串字)
{
字符串[]结果=输入。拆分(“”);
对于(inti=0;iIt很简单,你试过什么了吗?你的错误代码在哪里?你能告诉我第五位是什么,而不是第四位吗
/*@input: is the source string to search*
* @word is the key to search
* @returns the position of the word if prsent else -1 is returned
*/
public static int wordPosition(String input,String word)
{
String[] result=input.split(" ");
for(int i=0;i<result.length;i++)
{ if(result[i].contains(word))
return i+1;
}
return -1;
}