【问题标题】:finding matching characters between two strings查找两个字符串之间的匹配字符
【发布时间】:2019-10-28 22:47:32
【问题描述】:
public class findMatching {
   public static void main(String[] args) {
      String matchOne = "caTch";
      String matchTwo = "cat";
      findMatching(matchOne, matchTwo);
   }

   public static void findMatching(String matchOne, String matchTwo) {
      int lengthOne = matchOne.length();
      int lengthTwo = matchTwo.length();
      char charOne;
      char charTwo;

      while(!matchOne.equals(matchTwo)) {
         for(int i = 0; i < lengthOne && i < lengthTwo; i++) {
            charOne = matchOne.charAt(i);
            charTwo = matchTwo.charAt(i);
            if(charOne == charTwo && lengthOne >= lengthTwo) {
               System.out.print(charOne);
            } else if (charOne == charTwo && lengthTwo >= lengthOne){
               System.out.print(charTwo);
            } else {
               System.out.print(".");
            }
         }
      }
   }
}

我创建了一个名为 findMatching 的静态方法,该方法接受两个字符串参数,然后比较它们是否匹配字符。如果检测到匹配字符,它将打印所述字符,而不匹配的字符则用“。”表示。而是。

EX:对于caTchcat,预期的输出应该是ca...,其中不匹配的字符用“.”表示在较长的字符串中。

然而,现在我的程序的输出只打印出ca.,因为它只打印较短字符串的不匹配字符。我相信问题的根源可能在于我的 lengthOnelengthTwo 的 if 语句的逻辑。

【问题讨论】:

    标签: java string char


    【解决方案1】:

    当你在i &lt; lengthOne &amp;&amp; i &lt; lengthTwo 中遇到较短字符串的长度时,你的 for 循环将立即终止。所以你需要保持循环直到你到达较长字符串的末尾,但是当较短的字符串没有字符时停止比较。

    这样的东西就可以完成这项工作

    public static void findMatching(String matchOne, String matchTwo) {
      int lengthOne = matchOne.length();
      int lengthTwo = matchTwo.length();
      char charOne;
      char charTwo;
    
      for(int i = 0; i < lengthOne || i < lengthTwo; i++) {
        if(i < lengthOne && i < lengthTwo) {
            charOne = matchOne.charAt(i);
            charTwo = matchTwo.charAt(i);
            if (charOne == charTwo) {
               System.out.print(charTwo);
            } else {
               System.out.print(".");
            }
        } else {
           System.out.print(".");
        }
    
      }
    }
    

    我不确定 while 循环的意义是什么,因为它会使程序永远运行,但也许你想要它作为 if?

    【讨论】:

    • 谢谢,您解决了我的问题。你是对的,它不应该是一个while循环。我打算让它成为一个 if 语句,尽管它不是必需的。
    【解决方案2】:

    第一个 for 循环打印所有常见和不常见 (".") 字符,第二个 for 循环打印不常见字符 (".") 直到使用绝对 (abs) 的较大和较小字符串之间的差异功能

    代码:

              for(int i = 0; i < lengthTwo && i < lengthOne; i++){
                if(matchOne.charAt(i) == matchTwo.charAt(i)){
                 System.out.print(matchOne.charAt(i));
                }
                else{
                 System.out.print(".");
                }
              }
              for(int j = 0; j < java.lang.Math.abs(lengthOne - lengthTwo);j++){
               System.out.print(".");
              }
    

    【讨论】:

    • 如果字符串长度不同,这将导致IndexOutOfBoundsException
    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2019-11-27
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多