Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我需要从使用它的word中获取特定的word';s位置_Java_String - Fatal编程技术网

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)

你好,世界!。嘿

  • 你好
  • 世界
  • 那里
  • p.S.我不认为你对待
    作为一个单独的单词

    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;
        }