【问题标题】:How to replace non-ASCII characters in a sequence?如何替换序列中的非ASCII字符?
【发布时间】:2017-12-10 22:15:59
【问题描述】:

基本上,这段代码的作用是:

  • 接受意见。
  • 将长度大于 2 的每个字符序列替换为该字符重复的次数和字符本身(例如 jjjkkkkkllll = 3j5k4l)。输入不包含任何数值。
  • 返回结果。

代码:

private String replaceConsecutiveChars(String data) {
    char[] dataChars = data.toCharArray();

    int i = 0;
    int k = 0;
    Character charType = null;
    for(Character c : dataChars) {
        if(k == dataChars.length - 1 && i >= 2) {
            data = data.replace(repeat(String.valueOf(charType), ++i), (i + Character.toString(charType)));
            break;
        }

        if(i == 0) {
            charType = c;
            i++;
        }else if(c == charType) {
            i++;
        }else if(c != charType && i > 2) {
            data = data.replace(repeat(String.valueOf(charType), i), (i + Character.toString(charType)));

            i = 1;
            charType = c;
        }else if(c != charType && i <= 2) {
            i = 1;
            charType = c;
        }

        k++;
    }

    return data;
}

private String repeat(String s, int n) {
    return Stream.generate(() -> s).limit(n).collect(Collectors.joining(""));
}

但是,我的实现似乎只适用于有限的 ASCII 字符集,但我试图让它适用于 Unicode 字符集。例如:

  • 输入ddddddddkkkkkpppp会正确输出8d5k4p
  • 输入êêêêÌÌÌÌÌÌÌØØØ 会错误输出êêêêÌÌÌÌÌÌÌØØØ
  • 输入"rrrrrêêêêÌÌÌÌÌkkkkØØØ"会错误输出5rêêêêÌÌÌÌÌ4kØØØ

这是为什么?

此外,还有比我现在做的更好的方法吗?

【问题讨论】:

  • 为什么要使用字符包装类?
  • 所以我可以使用null
  • 你唯一使用的地方是你在循环中保存的角色。显得比较傻。你为什么不使用 char 并最初为它分配 '1' 的值,因为你知道你永远不会在你的循环中循环一个数字?

标签: java string unicode ascii


【解决方案1】:

您正在使用 == 比较 Character 的实例,这将无法按预期工作,因为运算符比较的是对象引用而不是值。

一个简单的快速解决方法是将 for 循环更改为:

for (char c : dataChars) {
}

注意类型的变化(从字符到字符)。这样charTypec 比较时,会自动将其拆箱为原语char

另一种解决方案是将每个 c == charType 替换为 c.equals(charType),而不是比较引用,而是比较值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多