如何获取字符串

时间:2015-12-09 05:17:43

标签: java string word

我试图找出如何在 Java 中的字符串中获取第n个单词。我被困在我应该如何创建代码来执行此操作。非常感谢,很多帮助!

public static void main(String[] args) {
    boolean allCorrect = true;
    allCorrect &= testNthWord("I love to walk to the park", 3, "to");
    allCorrect &= testNthWord("The theater is in the theater district.", 5,
            "the");
    allCorrect &= testNthWord("I am so happy I am getting this right!", 6,
            "am");
    allCorrect &= testNthWord("The quick brown fox jumped over the fence",
            15, "");
    allCorrect &= testNthWord(
            "1 is a lonely number but it also always returns 0 when used before the % operator.",
            1, "1");
    result(allCorrect, "getNthWord");
}

public static String getNthWord(String fullString, int nth) {
    String getIndex;
    for (int i = 0; i < nth - 1; i++) {
        int index = fullString.getIndex(" ");
        if (index == -1)
            return " ";
        fullString = fullString.substring(index + 1);
    }
    int index1 = fullString.getIndex(" ");
    if (index1 = -1)
        return fullString;
    else
        fullString.getIndex(0, index1);
    return "";

}

2 个答案:

答案 0 :(得分:1)

使用.split方法,您可以轻松完成此操作。例如:

 String[] x = "My Name Is Bob".split(" ");

现在您可以访问句子中的第N个单词作为数组中的第N个位置。

可以看到该方法的完整文档here

public static void main(String[] args) 
{
boolean allCorrect = true;
allCorrect &= testNthWord("I love to walk to the park", 3, "to");
    allCorrect &= testNthWord("The theater is in the theater district.", 5, "the");
    allCorrect &= testNthWord("I am so happy I am getting this right!", 6, "am");
    allCorrect &= testNthWord("The quick brown fox jumped over the fence", 15, "");
    allCorrect &= testNthWord("1 is a lonely number but it also always returns 0 when used before the % operator.", 1, "1");
    result(allCorrect, "getNthWord");
}
public static String getNthWord(String fullString, int nth)
{
   String[] temp = fullString.split(" ");
   if(nth-1 < temp.length)
   return temp[nth - 1];
   return null;
}

这将是更新的代码。

答案 1 :(得分:1)

希望这会对你有所帮助。

public static void main(String[] args) {
        int nth = 5;
        String s = "This is a sample sentence example to test nth numer, lets say 5th.";
        String[] words = s.split("\\s+");
        for (int i = 0; i < words.length; i++) {
            // you may omit any word you consider is not a word.
            words[i] = words[i].replaceAll("[^\\w]", "");
        }
        System.out.println(words.length);
        if(nth >= 1 && nth <= words.length)
            System.out.println("Nth word is: "+words[nth-1]);

    }