有 Java 编程相关的问题?

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

java获取字符串中特定单词后面的字符?

我有一个文本字符串和一个我需要在字符串中找到的特定单词。一旦我在字符串中找到下一个出现的单词,我需要以某种方式找到该单词后面的字符。我尝试使用scanner,但它不包含nextChar()方法,类似的东西可以满足我的目的。我还能尝试什么?这是我的代码,但它不符合我的要求

public void storeChar(String str)  //used to get the char after the seed and store it in the arraylist of chars
{
    Scanner sc = new Scanner(str);
    seed = wrdSd.getSeed();
    while(sc.hasNext())  //while there are words left to read
    {
        String next = sc.next();

        if(next.equals(seed))  //if the next word of the scanner = the seed
        {
            ch = sc.next().charAt(0);  //gets char at index 0 of the next word
            singleChar.add(ch); //adds the char to the char arraylist
        }   
    }
    sc.close();

}

提前谢谢


共 (2) 个答案

  1. # 2 楼答案

    使用^{}方法确定单词是否在字符串中。如果是,则使用返回的索引,添加单词的长度,并使用charAt方法将该结果用作字符串的索引。小心不要跑过头