简体   繁体   English

如何比较两个字符串并用 - 替换不匹配的字母?

[英]How to compare two strings and replace non-matching letters with -?

I'm trying to write a program to compare two strings, pick out the mismatching bits, and replace them with "-" 我正在尝试编写一个程序来比较两个字符串,找出不匹配的位,并用“ - ”替换它们

ex.) go("boo" , "foo") returns -oo ex。) go("boo" , "foo") returns -oo

Here's what I've come up with so far: 这是我到目前为止所提出的:

String go( String a, String b ) {
  String c = "";
  String q = "-";
  int al = a.length();
  for(int i = 0; i < al; i++){
     char ch = a.charAt(i);
     if(b.indexOf(a)!= -1) {
       c = c + String.valueOf(ch);
     } else {
       c = c + q;
     }
   }
 return c;
 }

Use a StringBuilder in order to quickly and easily mutate a string, and then return the toString() value. 使用StringBuilder以快速轻松地改变字符串,然后返回toString()值。 You can use setCharAt in order to change the characters at certain indexes. 您可以使用setCharAt来更改某些索引处的字符。

This code assumes that str1.length() == str2.length() as a pre-condition. 此代码假定str1.length() == str2.length()作为前提条件。

public String escapeDifferentCharacters(String str1, String str2) {
    StringBuilder result = new StringBuilder(str1);
    for (int i = 0; i < str1.length(); i++) {
        if (str1.charAt(i) != str2.charAt(i)) {
            result.setCharAt(i, '-');
        }
    }
    return result.toString();
}

you can do this with regex: 你可以用正则表达式做到这一点:

String str1 = "boo";
String str2 = "foo";

System.out.println(str1.replaceAll("[^"+str2+"]","-"));

     (or)

Pattern p = Pattern.compile("[^"+str1+"]");
Matcher m = p.matcher(str2);
System.out.println(m.replaceAll("-"));

output: 输出:

-oo -oo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM