我想比较两个用户定义的字符串并输出两个字符串之间共享的字符数,而不需要使用数组。然后我需要输出每个字符。我理解使用扫描仪的用户输入部分,但后来我就一无所知了。
例如,“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);
}
}
最佳答案
假设您有 word1
和 word2
:
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/