在java中查找字符串中的单词位置

时间:2016-06-14 13:25:13

标签: java

我在这里寻找另一个答案,但我真的不明白如何将其转换为我自己的代码。 我试图在短语中找到“COUNTRY”的位置:

String word = "COUNTRY";
String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOU COUNTRY";

输出该单词位于第5和第17位。

非常感谢

编辑:我意识到它也需要忽略这个案子。很抱歉没有早点说出来

3 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

public static void main(String args[]) {
    String word = "COUNTRY";
    String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOU COUNTRY";
    String[] listWord = sentence.split(" ");
    for (int i = 0; i < listWord.length; i++) {
        if (listWord[i].equals(word)) {
            System.out.println(i+1);
        }
    }
}

答案 1 :(得分:0)

如果您只想检查String是否包含Word,那么您可以使用String提供的.contains("");方法

String word = "COUNTRY";
String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOU COUNTRY";

System.out.println(sentence.contains(word));
//will return true;

如果你想查找句子中的所有单词,请使用:

String word = "COUNTRY";
String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOU COUNTRY";

if (sentence.contains(word)) {
    String[] sentenceWords = sentence.split(" ");

    for (String wordInSentence : sentenceWords) {
        if (wordInSentence.equals(word)) {
            System.out.println(wordInSentence);
        }
    }
}

或者,如果您想知道特定单词的确切位置,请尝试以下方法:

String word = "COUNTRY";
String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOU COUNTRY";

if (sentence.contains(word)) {
    String[] sentenceWords = sentence.split(" ");

    for (int i = 0; i < sentenceWords.length; i++) {
        if (sentenceWords[i].equals(word)) {
            System.out.println(word + " is located as the: " + i + "th string");
        }
    }
}

注意:请参阅我在String对象上使用.equals();,请参阅this发布以获取更多信息!

修改

要忽略此案例,您可以使用String.equalsIgnoreCase()代替String.equals()

答案 2 :(得分:0)

更好地使用java.lang。*中的这个函数,即在String类中。它是非静态的......

int indexOf(String str)            返回指定子字符串第一次出现的字符串中的索引。  int indexOf(String str,int fromIndex)            从指定的索引处开始,返回指定子字符串第一次出现的字符串中的索引。

String s1="Hello I love my country,i belong to my country",s2="country";
System.out.println( s1.indexOf(s2));