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

时间:2017-10-06 00:02:43

标签: java string object twitter indexof

我正在使用Java中的Twitter类型程序,其中正文是发送的推文。我正在尝试使用indexOf来查找主题标签的位置和空白区域的位置,这样我就可以通过连接打印出所有主题标签,并对访问者进行一次调用。当我运行程序时,我得到一行超出界限的错误:

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

我测试了子字符串,问题似乎与“位置”变量有关,但我不知道如何解决它。这是我的代码:

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

示例正文:“你好#world怎么样#you”

allHashtags =“#world#you”

如果对代码/我的解释不清楚,请告诉我,我会尽力澄清。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

第一种方法是使用split来获取所有单词并在检查后是否每个单词都以&#34开头;#"

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循环和搜索hashtag索引的另一种方法:

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表示我为什么喜欢/更喜欢第一个代码。