java - 计算并输出两个字符串之间的相似字符

标签 java string

我想比较两个用户定义的字符串并输出两个字符串之间共享的字符数,而不需要使用数组。然后我需要输出每个字符。我理解使用扫描仪的用户输入部分,但后来我就一无所知了。

例如,“hamper”为 string1,“happened”为 string2 将返回:

共享字符数 = 5

共享字符>>“h”、“a”、“p”、“p”、“e”、“e”

这是我到目前为止所拥有的。不过,它将每个字符打印在单独的行上。有没有一种方法无需数组即可将它们全部列在一行上,如上所示?:

    public class CountMatches {

  public static void main(String[] args)
  {
    //Declare both Strings.
    String word1;
    String word2;
    int count = 0;


    //Call for User Input.
    Scanner inputDevice = new Scanner(System.in);
    System.out.print("Input String 1 >> ");
    word1 = inputDevice.next();
    System.out.print("Input String 2 >> ");
    word2 = inputDevice.next();
    inputDevice.close();

    //Determine lengths and set label accordingly.
    String BigWord;
    String SmallWord;

    if (word1.length() > word2.length())
    {
        BigWord = word1;
        SmallWord = word2;
    }
    else
    {
        BigWord = word2;
        SmallWord = word1;
    }

    //Count and Display the like characters.
    for (int i = 0; i < SmallWord.length(); i++)
    {
        if (BigWord.contains(String.valueOf(SmallWord.charAt(i))))
        {
            System.out.println("both words contain the letter " + SmallWord.charAt(i));
            count++;
        }
    }

    //Display the count of like characters.     
    System.out.print("Number of like characters >> " + count);
  }

    }

最佳答案

假设您有 word1word2:

String biggerWord;
String smallerWord;
if (word1.length() > word2.length()) {
   biggerWord = word1;
   smallerWord = word2;
} else {
   biggerWord = word2;
   smallerWord = word1;
}        
for (int i = 0; i < smallerWord.length(); i++) {
  if (biggerWord.contains(String.valueOf(smallerWord.charAt(i)))) {
    counter++;
  }
}

这可以找出哪个单词更大。然后,对于 smallerWord 的长度,一次迭代一个字符,看看 biggerWord 是否包含该字符。如果是,则增加计数器。 然后,counter 应该在循环结束时获得公共(public)字符的数量。

这是徒手编写的,因此请注意语法和小逻辑错误。或者我误解了你的任务。不过应该非常接近。

关于java - 计算并输出两个字符串之间的相似字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19529647/

相关文章:

java - Java类中的变量@XmlElement(nillable = true)之前是什么意思

java - 安卓字符串初始化

java - 如何在 Java 中比较字符串?

java - Spring-Test-MVC/MockServletContext - 内容在测试中为空但在 Tomcat 上工作

java - 渲染具有大字体大小的字形 vector

C++:不推荐从字符串常量到 'LPSTR {aka char*}' [-Wwrite-strings] 的转换 - 警告。如何避免?

java - 如何在 java 中只打印字符串的特定部分?

javascript - 查找字符串中第一个不重复的字符,这里有什么错误?

regex - 在 PowerShell 字符串中的 32 个字符 + 空格后返回新行

java - 带图标的圆形 JButton;不直接指向时会被点击;将光标设置为 HAND_CURSOR 适用于图标之外的区域