在Java中输出两个字符串中的类似字符

时间:2013-10-22 18:58:59

标签: java string

我想比较两个用户定义的字符串,并输出两个字符串之间共享的字符数,而不需要使用数组。然后我需要输出每个字符。我理解使用Scanner的用户输入部分,但之后我一无所知。如果您不想提供实际代码,伪代码就足够了。

例如,“阻碍”为string1,“发生”为string2将返回

共享字符的

= 4(5)

共享字符>> “h”,“a”,“p”,“e”(“h”,“a”,“p”,“p”,“e”,“e”)

(两种方式都可以)

1 个答案:

答案 0 :(得分:3)

假设不是唯一的匹配:

//get word1
//get word2
//set variable for character count:  count = 0
//for each character in word1
    //for each character in word2
        //if the characters are the same
            //print character
            //increment count
//print count

假设只有唯一匹配:

//get word1
//get word2
//set variable for character count:  count = 0
//create empty list of already found characters:  found_list = {}
//for each character in word1
    //for each character in word2
        //if the characters are the same
            //if character is not in found_list
                //print character
                //add character to found_list
                //increment count
//print count

我建议查找for loops.charAt()方法:

http://www.tutorialspoint.com/java/java_loop_control.htm

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29