显示字符串中匹配的字符

时间:2017-07-22 18:19:48

标签: java

学习java非常新,我正在研究一个简单的程序,它显示两个用户输入字符串之间的匹配字符数。最后,它将显示匹配的字符总数以及匹配的字母。我坚持如何将内部for循环的值传递回要调用的main方法。

import java.util.Scanner;
public class CountMatches
{
    public static void main(String[] args)
    {
        int matches = 0;
        String aString;
        String anotherString;


        Scanner inputDevice = new Scanner(System.in);
        System.out.print("Enter a String >> ");
        aString = inputDevice.nextLine();
        System.out.print("Enter another string>> ");
        anotherString = inputDevice.nextLine();

        for(int i = 0; i < aString.length(); ++i)
        {

            for(int j = 0; j < anotherString.length(); ++j)
            {
                if(aString.charAt(i) == anotherString.charAt(j))
                    matches++;

            }

        }

       System.out.println(matches + " character(s) in " + aString + " are 
       also in " + anotherString);

   }
}

编辑:我还应该提到我正在进行的这项任务,我还没有达到我正在使用数组的程度。我们刚刚介绍了循环以及if语句。所以我很早就学习java了。

5 个答案:

答案 0 :(得分:1)

一个简单,最好和更少的代码,例如:

Set<Character> aStringSet = new TreeSet<Character>();
for(int i = 0; i < aString.length(); i++) {
    aStringSet.add(aString.charAt(i));
}

Set<Character> anotherSet = new TreeSet<Character>();
for(int i = 0; i < anotherString.length(); i++) {
    anotherSet.add(anotherString.charAt(i));
}

aStringSet.retainAll(anotherSet);
System.out.print(aStringSet.size() + " character(s) in " + aString + " are also in " + anotherString);
System.out.println(" matched characters are " + aStringSet.toString());

输出:

Enter a String >> table
Enter another string>> fable
4 character(s) in table are also in fable matched characters are [a, b, e, l]

我使用过TreeSetTreeSetretainAll()获取匹配的元素。

  

Oracle Doc:

retainAll(Collection<?> c)
     

仅保留此集合中包含的元素   指定集合(可选操作)。

答案 1 :(得分:0)

你的逻辑不正确。当你在它的时候,可能想要探索一些其他的数据结构,比如Stack和ArrayList。会看起来像这样。

    int matches = 0;
    String aString;
    String anotherString;


    Scanner inputDevice = new Scanner(System.in);
    System.out.print("Enter a String >> ");
    aString = inputDevice.nextLine();
    System.out.print("Enter another string>> ");
    anotherString = inputDevice.nextLine();

    System.out.println(aString);
    System.out.println(anotherString);

    // we will store astring characters in a stack data structure
    Stack<Character> aStringStack = new Stack<Character>();
    // a list to store the matched characters
    List<Character> tempList = new ArrayList<>();

    //First adding all the chars from astring to the Stack
    for(int i = 0; i < aString.length(); i++)
    {
        aStringStack.push(aString.charAt(i));
    }


    for(int i = 0; i < aStringStack.size(); i++)
    {
        //Now iterating over the astring stack and popping the 
        // values from the top one at a time
        char temp = aStringStack.pop();

        for(int j = 0; j < anotherString.length(); j++)
        {
            //If the popped value is present in the anotherstring
            // then incrementing the match counter and storing the
            //matched character in our matched character array list
            if(temp == anotherString.charAt(j))
            {
                matches++;
                tempList.add(temp);

                // Also important to break the loop here to avoid
                // getting duplicates
                break;
            }

        }

    }

    System.out.println(matches + " character(s) in " + aString + " are  also in " + anotherString);
    System.out.println(tempList);

还建议将这个答案与@ Serge的答案进行比较,以了解如何使用不同的数据结构来解决同样的问题。

答案 2 :(得分:0)

您需要为角色及其计数器提供某种数据库。有多种方法可以做到这一点。以下使用HashMap来执行此操作,其中字符是键,计数器是值。这不是一种非常有效的方法,但它服务于解释的目的。

    // allocate the char/counter map
    HashMap<Character, Integer> cMap = new HashMap<>();

    for (int i = 0; i < aString.length(); ++i) {

        for (int j = 0; j < anotherString.length(); ++j) {
            if (aString.charAt(i) == anotherString.charAt(j)) {
                // see if the char already has an associated counter
                Integer count = cMap.get(aString.charAt(i));
                if (count == null)
                    count = 0; // if no counter is found, create one and set it to '0' (before incrementing)
                count++; 

                cMap.put(aString.charAt(i), count); // put the new counter value in the map
                matches++;
            }
        }
    }

    // traverse all map entries and print the key/value (char/counter) paires
    for (Map.Entry<Character, Integer> entry : cMap.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }

答案 3 :(得分:0)

存储匹配字符的一种方法是使用数据结构。当您在两个字符串中遇到匹配的字符时,可以将该字符添加到集合中。集合是用于保存对象的数据结构,在这种情况下;字符。有许多不同类型的数据结构,但主要类型是Set,List和Queue。

我使用ArrayList为您编写了一个解决方案:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CountMatches {
    public static void main(String[] args) {
        String aString;
        String anotherString;
        List<Character> matchingChars = new ArrayList<Character>();

        Scanner inputDevice = new Scanner(System.in);
        System.out.print("Enter a String >> ");
        aString = inputDevice.nextLine().toLowerCase();
        System.out.print("Enter another string>> ");
        anotherString = inputDevice.nextLine().toLowerCase();

        for (int i = 0; i < aString.length(); ++i) {
            for (int j = 0; j < anotherString.length(); ++j) {
                if (aString.charAt(i) == anotherString.charAt(j) && !matchingChars.contains(aString.charAt(i))) {
                    matchingChars.add(aString.charAt(i));
                }
            }
        }
        System.out.println(matchingChars.size() + " character(s) in " + aString + " are also in " + anotherString);
        System.out.println("The Matching character(s) are " + matchingChars);
    }
}

我们可以轻松打印列表的内容,因为它拥有自己的toString()方法,该方法返回一个包含所有匹配字符的字符串!

Enter a String >> Hello
Enter another string>> chelo
4 character(s) in hello are also in chelo
The Matching character(s) are [h, e, l, o]

因为我们将字符添加到列表中,您可以检查其大小,所以不再需要使用“匹配”变量引用进行计数,因为我们只能调用matchingChars.size()。

为了防止同一个字符串被添加到列表中两次,我们必须使用list.contains()将列表添加到列表中,如果列表中没有它,则只需将其添加到列表中。

另外,作为建议,(我在上面的示例中)您可以使用String.toLowercase()方法将字符串转换为小写,以便在比较字符时忽略字符的大小写

如果您想了解有关收藏的更多信息,[收藏的Java教程](https://docs.oracle.com/javase/tutorial/collections/)可能值得一看。

答案 4 :(得分:0)

不使用数组或其他任何东西,内部for循环如下所示:

for(int j = 0; j < anotherString.length(); ++j)
        {
            if(aString.charAt(i) == anotherString.charAt(j))
            {
            matches++;
            aChar = aString.charAt(i);              
            foundStr = foundStr + " " + aChar;
            }

        }

然后在主方法中使用foundStr来显示aString和anotherString之间的所有匹配字符。

相关问题