【问题标题】:In java character replace using charAt [duplicate]在java中使用charAt替换字符[重复]
【发布时间】:2018-10-10 16:52:54
【问题描述】:

我正在尝试输入两个字符串,我正在检查第一个字符串的任何字符是否等于第二个字符串字符,然后将其替换为 '*' 我的代码是

for(int i=0;i<l;i++)
    {
        for(int j=0;j<l;j++)
        {
            if(s1.charAt(i) == s2.charAt(j))
            {
                char c=s2.charAt(j);
                c='*';
                System.out.println(s2);
            }
        }
    }

但它没有被替换我应该怎么做才能使代码正常运行?

【问题讨论】:

  • 字符串在Java中是不可变的,你不能替换一个字符,你需要创建一个新的字符串来代替
  • 发帖前请search。更多关于搜索here.
  • 即使字符串不是不可变的(如在 C 中),这也是将charAt(j) 的值复制到局部变量中,然后更新局部变量。

标签: java


【解决方案1】:

String 在 Java 中是不可变的。因此,要更改 String 中间的单个字符,您必须将其拆分然后加入:

String str = "abcde";
String newStr = str.substring(0, 2) + "_" + str.substring(3); // "ab_de"

一般情况下,您不能更改字符串。所有修改都会创建 new(修改后的)字符串。特别是在循环中修改字符串是不好的做法;每次迭代都会得到一个新的字符串实例。

为了解决您的问题,我提议将第二个字符串中的所有唯一字符收集到 Set 中,然后使用 StringBuilder 构建结果字符串:

public static String modify(String one, String two) {
    Set<Character> uniqueChars = new HashSet<>();

    for (int i = 0; i < two.length(); i++)
        uniqueChars.add(two.charAt(i));

    StringBuilder buf = new StringBuilder(one.length());

    for(int i = 0; i < one.length(); i++)
        buf.append(uniqueChars.contains(one.charAt(i)) ? '*' : one.charAt(i));

    return buf.toString();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多