2017-10-06 42 views
0

我正在使用Java中的Twitter类型程序,其中正文是正在发送的推文。我正在尝试使用indexOf来查找hashtag的位置和空格的位置,以便我可以通过串联打印出所有hashtags,并且只需调用一次访问器即可。当我运行程序我得到一个出界错误的行:IndexOf在整个字符串中移动不会识别字符(Java)

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怎么样#你”

allHashtags = “#world#你”

如果有什么不清楚的代码/我的解释,请让我知道,我会尽力澄清它。感谢您的帮助!

+0

为什么你不只是使用正则表达式?你是否想要连接到'allHashtags'而不是仅仅覆盖它?为什么使用'bodyTemp = bodyTemp.substring(space + 1);'而不是只将第二个参数提供给'indexOf'? –

+0

那么,如果其中一个方法调用indexOf()返回-1,因为该字符串不包含“#”也不包含空格“”,那么你将尝试从一个或一直到一个负位置得到一个子字符串。 – JKostikiadis

+0

@Andy Turner我不使用rejex,因为我不被允许。是的,我试图连接(我只是更新了代码,因为我没有复制正确的行)。我不确定你最后一个问题的含义。 – pyr0

回答

0

通过拆分把所有的话和检查后,如果他们中的每一个以“#”

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

PS是凌晨3点不要指望最佳代码至少今天:P

重要:如果字是分开的b y选项卡或新行第二个代码显然不会工作:P那是为什么我喜欢/喜欢第一个。

+0

非常感谢你的帮助!你非常有帮助! – pyr0