Java如何比较字符串,字符串比较问题。

huangapple go评论80阅读模式
英文:

Java how to compare string, String compare problem

问题

我在Java中进行字符串比较时遇到了问题。我有两个几乎相似的字符串,但它们并不相等,因为一个包含了- (44)字符,另一个包含了- (8211)字符。有人可以帮我处理一下这种情况,使得这两个字符串相等吗?我在代码中尝试了以下内容,但没有成功:

cellValue.replaceAll("\u0045", "\u8211");
byte[] bytes = cellValue.getBytes(Charset.defaultCharset());
String cellValueUtf8 = new String(bytes, Charset.defaultCharset());
英文:

I have problem with string comparison in Java. I have 2 nearly similar strings, but they are not equal, because one contains - (44) char and another contains - (8211) char. Can someone help me with case, that this strings are equals. I tried this in code, but it doesn't work:

cellValue.replaceAll("\u0045", "\u8211");
byte[] bytes = cellValue.getBytes(Charset.defaultCharset());
String cellValueUtf8 = new String(bytes, Charset.defaultCharset());

答案1

得分: 0

String是常量;它们的值在创建后不能被更改。因此,String#replaceAll会返回一个新的String,即这个操作不会改变cellValue。此外,请注意,String#replaceAll的第一个参数是一个正则表达式。

您需要使用 String#replace,它会将给定字符串中所有出现的oldChar替换为newChar,而不是使用String#replaceAll

cellValue.replaceAll("\u0045", "\u8211");

替换为

cellValue = cellValue.replace('\u0045', '\u8211');

以便将更改后的值赋给cellValue

英文:

Strings are constant; their values cannot be changed after they are created. Thus, String#replaceAll returns a new String i.e. this operation doesn't change cellValue. Also, note that String#replaceAll takes a regex as the first parameter.

You need String#replace, which replaces all occurrences of oldChar in the given string with newChar, instead of String#replaceAll.

Replace

cellValue.replaceAll("\u0045", "\u8211");

with

cellValue = cellValue.replace('\u0045', '\u8211');

in order for the changed value to be assigned to cellValue.

答案2

得分: -1

我写了这个方法,它按照我预期的方式工作:

public static String normalizeDashChar(String toNormalize) {
    char[] bytes = toNormalize.toCharArray();
    for(int i = 0; i < bytes.length; i++) {
        if(bytes[i] == (char)45) {
            bytes[i] = (char)8211;
        }
    }

    return new String(bytes);
}
英文:

I wrote this method, and it works as I expect:

public static String normalizeDashChar(String toNormalize) {
    char[] bytes = toNormalize.toCharArray();
    for(int i = 0; i &lt; bytes.length; i++) {
        if(bytes[i] == (char)45) {
            bytes[i] = (char)8211;
        }
    }

    return new String(bytes);
}

huangapple
  • 本文由 发表于 2020年10月23日 00:02:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64486118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定