我想比较两个用户定义的字符串并输出两个字符串之间共享的字符数,而不使用数组。然后我需要输出这些字符中的每一个。我使用扫描仪了解用户输入部分,但之后我一无所知。
例如,“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);
}
}