【问题标题】:How to - Loop through a String and identify a specific character and add to the string如何 - 遍历字符串并识别特定字符并添加到字符串中
【发布时间】:2019-03-28 18:55:41
【问题描述】:

我目前正在尝试遍历 String 并标识该字符串中的特定字符,然后在最初标识的字符之后添加特定字符。

例如使用字符串:aaaabbbcbbcbb 我要识别的角色是:c

因此,每次检测到 c 时,都会将后面的 c 添加到字符串中,并且循环将继续。

因此 aaaabbbcbbcbb 将变为 aaaabbbccbbccbb

我一直在尝试使用 indexOf()substringcharAt(),但我目前要么用 c 覆盖其他字符,要么只检测到一个 c。

【问题讨论】:

  • 请分享您到目前为止所尝试的内容。

标签: java loops for-loop substring indexof


【解决方案1】:

遍历所有字符。将每个添加到StringBuilder。如果它与您要查找的字符匹配,请再次添加。

final String test = "aaaabbbcbbcbb";
final char searchChar = 'c';

final StringBuilder builder = new StringBuilder();
for (final char c : test.toCharArray())
{
    builder.append(c);
    if (c == searchChar)
    {
        builder.append(c);
    }
}
System.out.println(builder.toString());

输出

aaaabbbccbbccbb

【讨论】:

    【解决方案2】:

    您可能正在尝试在 java 中修改字符串。 Java 中的字符串是immutable,不能像c++ 中那样更改。

    您可以使用 StringBuilder 插入字符。例如:

    StringBuilder builder = new StringBuilder("acb");
    builder.insert(1, 'c');
    

    【讨论】:

    • 这只是在第一个和第二个字符之间添加一个'c'。这不是他们要求的。
    • 当你找到c 时插入一个额外的c 可能是解决他问题的一种方法。 @迈克尔
    【解决方案3】:

    我知道你已经要求循环,但是像替换这样简单的东西还不够吗?

    String inputString = "aaaabbbcbbcbb";
    String charToDouble = "c";
    
    String result = inputString.replace(charToDouble, charToDouble+charToDouble);
    // or `charToDouble+charToDouble` could be `charToDouble.repeat(2)` in JDK 11+
    

    Try it online.

    如果你坚持使用循环:

    String inputString = "aaaabbbcbbcbb";
    char charToDouble = 'c';
    
    String result = "";
    for(char c : inputString.toCharArray()){
      result += c;
      if(c == charToDouble){
        result += c;
      }
    }
    

    Try it online.

    【讨论】:

    • 一个更简单的解决方案!我从来没有遇到过 .replace() 非常感谢。
    【解决方案4】:

    之前建议String.replace 的答案是最好的解决方案,但如果您需要以其他方式(例如练习),那么这里有一个“现代”解决方案:

    public static void main(String[] args) {
        final String inputString = "aaaabbbcbbcbb";
        final int charToDouble = 'c';  // A Unicode codepoint
        final String result = inputString.codePoints()
                .flatMap(c -> c == charToDouble ? IntStream.of(c, c) : IntStream.of(c))
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                .toString();
        assert result.equals("aaaabbbccbbccbb");
    }
    

    这会依次查看每个字符(在 IntStream 中)。如果它与目标匹配,它将使字符加倍。然后它将每个字符累积到一个 StringBuilder 中。

    可以进行微优化以预先分配 StringBuilder 的容量。我们知道新字符串的最大可能大小是旧字符串的两倍,因此StringBuilder::new 可以替换为() -> new StringBuilder(inputString.length()*2)。但是,我不确定是否值得牺牲可读性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2020-12-13
      • 2014-06-28
      • 2021-12-05
      相关资源
      最近更新 更多