英文:
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
。
英文:
String
s 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 < bytes.length; i++) {
if(bytes[i] == (char)45) {
bytes[i] = (char)8211;
}
}
return new String(bytes);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论