在两个字符串中显示常见字符,不重复

时间:2022-02-21 21:38:50

I need to write a program that should ask two strings from user and show the common characters in this.

我需要编写一个程序,该程序应该询问用户的两个字符串并显示其中的常用字符。

It must not have duplicates: even if ‘a’ is found more than once in both strings, it should be displayed only once.

它不能有重复:即使在两个字符串中找到“a”多次,它也只能显示一次。

My Java knowledge is very limited, so I'm not looking for efficiency but for understandability.

我的Java知识非常有限,所以我不是在追求效率,而是在寻求可理解性。


Here is what I came up with at the moment.

这就是我现在提出的问题。

//Get String 1
System.out.print( "Enter a string: " );
string1 = sc.next();

//Get String 2
System.out.print( "Enter another string: " );
string2 = sc.next();

System.out.print ( "Common characters: " );
//Common chars           
for ( a = 0 ; a < string1.length() ; a++){
    for ( b = 0 ; b < string2.length() ; b++){
        if ( string1.charAt(a) == string2.charAt(b) ){
            System.out.print(string1.charAt(a));
        }

Can anyone help me ?

谁能帮我 ?

3 个解决方案

#1


2  

You can use the chars() stream of the input string, e.g.:

您可以使用输入字符串的chars()流,例如:

public class StringCharCount {
  public static void main(final String[] args) {
    final String s1 = args[0];
    final String s2 = args[1];

    s1.chars()
        .distinct()
        .mapToObj(ch -> String.valueOf((char) ch))
        .filter(s2::contains)
        .forEach(System.out::println);
  }
}

This works with Java 8 or later.

这适用于Java 8或更高版本。

  • chars() creates a stream of characters from the string
  • chars()从字符串创建一个字符流

  • distinct() ensures, that each value occurs only once
  • distinct()确保每个值只出现一次

  • mapToObj(...) is required, because the String#contains() method requires a String as input. So we are converting the stream value to a String. Unfortunately, Java has issues with the primitive types, so the stream of chars is in fact a stream of int. So we have to cast each value to char.
  • mapToObj(...)是必需的,因为String#contains()方法需要String作为输入。所以我们将流值转换为String。遗憾的是,Java存在基本类型的问题,因此字符串流实际上是int的流。所以我们必须将每个值转换为char。

  • forEach(...) prints each value to System.out
  • forEach(...)将每个值打印到System.out

#2


1  

I would use a Set<Character>. This would naturally handle the duplicate issue and has a simple retainAll method to do the heavy lifting for you.

我会使用Set 。这自然会处理重复的问题,并有一个简单的retainAll方法来为您完成繁重的工作。

private Set<Character> characterSet(String s) {
    Set<Character> set = new HashSet<>();
    // Put each character in the string into the set.
    for (int i = 0; i < s.length(); i++) {
        set.add(s.charAt(i));
    }
    return set;
}


public Set<Character> common(String a, String b) {
    // Make a set out of each string.
    Set<Character> aSet = characterSet(a);
    Set<Character> bSet = characterSet(b);
    // Work out the common characters using retainAll.
    Set<Character> common = new HashSet<>(aSet);
    common.retainAll(bSet);
    return common;
}

public void test(String[] args) throws Exception {
    System.out.println(common("abcdef", "afxyzfffaa"));
}

#3


0  

You can use Set

你可以使用Set

        String str1 = "abcdefg";
        String str2 = "abcaaadefg";

        StringBuilder result = new StringBuilder();
        Set<Character> sets = new HashSet<Character>();
        for(char ch : str1.toCharArray()){//init
            sets.add(ch);
        }
        for(char ch : str2.toCharArray()){
            if(sets.contains(ch)){//str1 char contains str2 char
                result.append(ch);
                sets.remove(ch);//avoid duplicates
            }
        }
        System.out.println(result.toString());

#1


2  

You can use the chars() stream of the input string, e.g.:

您可以使用输入字符串的chars()流,例如:

public class StringCharCount {
  public static void main(final String[] args) {
    final String s1 = args[0];
    final String s2 = args[1];

    s1.chars()
        .distinct()
        .mapToObj(ch -> String.valueOf((char) ch))
        .filter(s2::contains)
        .forEach(System.out::println);
  }
}

This works with Java 8 or later.

这适用于Java 8或更高版本。

  • chars() creates a stream of characters from the string
  • chars()从字符串创建一个字符流

  • distinct() ensures, that each value occurs only once
  • distinct()确保每个值只出现一次

  • mapToObj(...) is required, because the String#contains() method requires a String as input. So we are converting the stream value to a String. Unfortunately, Java has issues with the primitive types, so the stream of chars is in fact a stream of int. So we have to cast each value to char.
  • mapToObj(...)是必需的,因为String#contains()方法需要String作为输入。所以我们将流值转换为String。遗憾的是,Java存在基本类型的问题,因此字符串流实际上是int的流。所以我们必须将每个值转换为char。

  • forEach(...) prints each value to System.out
  • forEach(...)将每个值打印到System.out

#2


1  

I would use a Set<Character>. This would naturally handle the duplicate issue and has a simple retainAll method to do the heavy lifting for you.

我会使用Set 。这自然会处理重复的问题,并有一个简单的retainAll方法来为您完成繁重的工作。

private Set<Character> characterSet(String s) {
    Set<Character> set = new HashSet<>();
    // Put each character in the string into the set.
    for (int i = 0; i < s.length(); i++) {
        set.add(s.charAt(i));
    }
    return set;
}


public Set<Character> common(String a, String b) {
    // Make a set out of each string.
    Set<Character> aSet = characterSet(a);
    Set<Character> bSet = characterSet(b);
    // Work out the common characters using retainAll.
    Set<Character> common = new HashSet<>(aSet);
    common.retainAll(bSet);
    return common;
}

public void test(String[] args) throws Exception {
    System.out.println(common("abcdef", "afxyzfffaa"));
}

#3


0  

You can use Set

你可以使用Set

        String str1 = "abcdefg";
        String str2 = "abcaaadefg";

        StringBuilder result = new StringBuilder();
        Set<Character> sets = new HashSet<Character>();
        for(char ch : str1.toCharArray()){//init
            sets.add(ch);
        }
        for(char ch : str2.toCharArray()){
            if(sets.contains(ch)){//str1 char contains str2 char
                result.append(ch);
                sets.remove(ch);//avoid duplicates
            }
        }
        System.out.println(result.toString());