使用正则表达式

时间:2018-01-23 20:17:40

标签: java arrays algorithm indexing split

我有String str="[12] word1 word2 (12.4%)"

我需要的是只获取word1 word2并用下划线输出替换空格应该像这样word1_word2

之后如何动态制作它,例如str可能会增加像word1_word2_word3_etc

这样的单词

如何尽可能缩短代码?

1 个答案:

答案 0 :(得分:1)

您可以使用split()来分割单词。然后使用字符串构建器将它们组合在一起

一般的想法应该是这样的(可能不是100%正确):

String[] words = str.split(" ");
StringBuilder sb = new StringBuilder();

// So don't include the first and last word as they are "[12]" and "(12.4%)".
// It doesn't matter how many words you have as we use words.length
for (int i = 1; i < words.length - 1; ++i) 
{
    // you could figure out a better method to add "_"
    if (i != 1)
    {
        sb.append("_");
    }
    sb.append(words[i]);
}
String result = sb.toString();