有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获取字符串中的第n个单词

我正试图找出如何在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 "";

}

共 (1) 个答案

  1. # 1 楼答案

    使用。分割法你可以很容易地做到这一点。例如:

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

    这将是更新的代码