IndexOf 在整个字符串中移动不是识别字符 (Java)

IndexOf moving throughout a string is not identifying characters (Java)

我正在 Java 开发一个 Twitter 类型的程序,其中正文是要发送的推文。我正在尝试使用 indexOf 来查找主题标签的位置和 white-space 的位置,以便我可以通过连接一次调用访问器来打印出所有主题标签。当我是 运行 程序时,我得到了该行的越界错误:

allHashtags+=bodyTemp.substring(position, space+1)+" ";

我已经测试了子字符串,问题似乎与 "position" 变量有关,但我不确定如何解决它。这是我的代码:

 public String getAllHashtags() {
        int indexFrom=0;
        int position=0;
        String allHashtags="";
        String bodyTemp=body;
        while(position>-1) {
            position=bodyTemp.indexOf("#");
            int space=bodyTemp.indexOf(" ");
            allHashtags+=bodyTemp.substring(position, space+1)+" ";
            bodyTemp=bodyTemp.substring(space+1);
        }
        return allHashtags;
    }

正文示例:"Hello #world How are #you"

allHashtags= "#world #you"

如果 code/my 的解释有任何不清楚的地方,请告诉我,我会尽力澄清。感谢您的帮助!

第一种方法是使用 split 来获取所有单词,然后检查每个单词是否以“#”开头

public static String getAllHashtags() {

    String body = "Hello #world How are #you";
    String tokens[] = body.split("\s+");
    String allHashtags = "";

    for (String token : tokens) {
        if (token.startsWith("#")) {
            allHashtags += token; 
        }
    }
    return allHashtags;
}

另一种使用 while 循环并搜索主题标签索引的方法:

public static String getAllHashtags() {

    String body = "Hello #world How are #you";
    String allHashtags = "";

    int index = -1;
    while ((index = body.indexOf('#')) != -1) {
        // cut the string up to the first hashtag
        body = body.substring(index+1);
        // we need to check if there is a empty space at the end or not
        if(body.indexOf(' ') != -1) {
            allHashtags += "#" + body.substring(0,body.indexOf(' '));
        }else {
            allHashtags += "#" + body;
        }

    }
    return allHashtags;
}

P.S 现在是凌晨 3 点,至少今天不要期待最佳代码 :P

重要:如果单词由制表符或换行分隔,第二个代码显然不会工作 :P 这就是为什么我 like/prefer 第一个一.