如何找出两个字符串之间不同的单词?

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

How to find words that are different between two Strings?

问题

我希望你一切安好。

我正在寻找一种简单的方法来比较两个字符串,并打印出两者之间不同的单词,例如我有:

String one = edittext1.getText().toString();
String two = editText2.getText().toString();

然后输出应该是,存在于 edittext1 中但不存在于 edittext2 中的单词。

英文:

I hope you are fine.

I am searching for a simple way to compare two Strings and print out the words which are unique between the two, for example I have :

String one = edittext1.getText().toString();
String two = editText2.getText().toString();

Then the output should be what is the words that exists in edittext1 and not exist in edittext2.

答案1

得分: -1

如果只是单词,您可以将字符串拆分为string[],每个单元格将只包含一个单词,然后比较这些单词。操作如下:

String one = "this is first text example";
String two = "this is next text example";
String[] oneVals = one.split(" ");
String[] twoVals = two.split(" ");
int i = oneVals.length;
if (oneVals.length != twoVals.length) {
    // 确定要执行什么操作
}
String wordsNotMatching = "";
for (int j = 0; j < i; j++) {
    if ((!oneVals[j].equals(twoVals[j])))
        wordsNotMatching += oneVals[j] + " ";
}
// wordNotMatching 将包含所有不同的单词。
英文:

if it's only words you can split the strings to string[] that each cell will contain 1 word only and then compare those words. Goes as follows:

String one = &quot;this is first text example&quot;;
String two = &quot;this is next text example&quot;;
String[] oneVals = one.split(&quot;\\ &quot;);
String[] twoVals = two.split(&quot;\\ &quot;);
int i = oneVals.length;
if(oneVals.length != twoVals.length)
{
    // determine what to do
}
String wordsNotMatching = &quot;&quot;;
for(int j=0; j&lt;i; j++)
{
    if((!oneVals[j].equals(twoVals[j])))
        wordsNotMatching += oneVals[j] + &quot; &quot;;
}
// wordNotMatching will contain all different words.

huangapple
  • 本文由 发表于 2020年10月22日 20:15:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64482015.html
匿名

发表评论

匿名网友

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

确定