【发布时间】:2017-05-30 06:07:43
【问题描述】:
问题是它必须比较两个字符串(文本文件中的示例),并显示其中的差异。
是否应该在输出中也打印出等号元素?
不使用 for 循环,也许有不同的解决方案来实现它。
怎么做?
代码
import java.util.ArrayList;
public class ParseTest {
String saR1 = "This is a Test for checking the content and a Test to compare it";
String saR2 = "This is the second Test for checking the seconds content and a second Test to compare it";
String diff1 = "";
String diff2 = "";
int o3;
int o4;
public static void main(String[] args) {
new ParseTest().parseMethod();
}
private void parseMethod() {
String[] sa1 = saR1.split("\\s");
String[] sa2 = saR2.split("\\s");
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
for(int o = 0; o<sa1.length; o++) {
al1.add(sa1[o]);
}
for(int o = 0; o<sa2.length; o++) {
al2.add(sa2[o]);
}
if(al1.size() <= al2.size()) {
for(int oi = 0; oi<al2.size()+al1.size(); oi++) {
for(o4 = 0; o4<al2.size(); o4++) {
for(o3 = 0; o3<al1.size(); o3++) {
if(al1.size() == al2.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
if(al2.size() > al1.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
}
}
}
}
for(String or1 : al1) {
diff1 += " " + or1;
} System.out.println("This is saR1 :" + saR1);
System.out.println("This is the difference in saR1 :" + diff1);
for(String or2 : al2) {
diff2 += " " + or2;
} System.out.println("This is saR2 :" + saR2);
System.out.println("This is the difference in saR2 :" + diff2);
}}
【问题讨论】:
-
您已经在使用
bw.readLine()阅读它们,并且可以使用equals、matches和其他一些String方法来处理它们,但不清楚您真正要问的是什么/ 为我而奋斗。 -
请放一个真实的minimal reproducible example;包括您正在使用的确切输入的描述;预期和实际行为。
-
提示:
String#split。否则,建议迭代和使用StringBuilder/List<String>。 -
现在它似乎可以工作了,我使用了 for 循环、String-ArrayLists 和 -Arrays 与 split。为什么投反对票。谢谢
标签: java string parsing compare