gpt4 book ai didi

Java,计算字符串中唯一字符之间的差异

转载 作者:太空宇宙 更新时间:2023-11-04 14:19:49 27 4
gpt4 key购买 nike

假设我有 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());

正则表达式来源: How to Match a Single Unicode Grapheme

关于Java,计算字符串中唯一字符之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325154/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com