假设我有 2 个字符串,我需要计算它们唯一字符之间的差异。很简单:
String s1 = "abcd";
String s2 = "aaaacccbbf";
//answer: 1
答案是1,因为s1变量中没有“f”。
但是像மா 或汉字或任何其他非 ASCII 字符这样的字符呢?如果我循环遍历这些字符串,像 கு 这样的一个字符将作为单独的字符计算 2-3 次,从而给出错误的答案:
String s1 = "ab";
String s2 = "aaaகுb";
//answer: 2 (wrong!)
我尝试过的代码:
class a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
sc.close();
String missingCharacters= "";
for(char c : s2.toCharArray()) {
if(!missingCharacters.contains(c+"") && !s1.contains(c+""))
missingCharacters+= c;
}
System.out.println(missingCharacters.length());
}
}
最佳答案
您的符号கு
是泰米尔文字的复合形式,其中包含两个Unicode字符க் + உ
(0B95 + 0BC1)。如果您计划使用泰米尔语脚本,您必须找到具有模式的所有相似字符:
String s1 = "ab";
String s2 = "aaaகுb";
Pattern pattern = Pattern.compile("\\p{L}\\p{M}*");
Matcher matcher = pattern.matcher(s2);
Set<String> missingCharacters=new TreeSet<>();
while (matcher.find()) {
missingCharacters.add(matcher.group());
}
matcher = pattern.matcher(s1);
while (matcher.find()) {
missingCharacters.remove(matcher.group());
}
System.out.println(missingCharacters.size());
关于Java,计算字符串中唯一字符之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325154/