有 Java 编程相关的问题?

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

使用正则表达式在java中分隔字符串的数组

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

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

在那之后,我如何使它动态地,比如str may,单词可能会像word1_word2_word3_etc一样递增

如何使代码尽可能短


共 (1) 个答案

  1. # 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();