简体   繁体   中英

Comparing multiple strings character by character java

I wanted compare multiple strings character by character and want to output a string which contains the characters which are present in most of the string. For example I used three strings: Input:S1= where, S2= wHere, S3=whera Output:S=where.

I could do it for 3 strings using the code :

public class stringc {

    static String S1="where";
    static String S2="wHere";
    static String S3="whera";
    static StringBuilder S=new StringBuilder();

    public static void main(String[] args)
    {
        for (int i=0;i<5;i++)
        {

            if(S1.charAt(i)==S2.charAt(i)||S1.charAt(i)==S3.charAt(i))
            {
                S.append(S1.charAt(i));
            }
        }
    }
}

Can anybody help me how to use it for more than 10 strings.

使用数组/字符串列表,而不是int i=0;i<5;i++使用int i=0;i<array.length;i++ //将list.size()用于列表

How I'd do it:

  1. for each of your strings, call toCharArray()
  2. Add the resulting char[] to a 2D char array
  3. For each word in the 2D array, add the character you are inspecting to a map, incrementing a counter if the character is already in the maps keySet()
  4. The character with the most occurrences (highest counter) in the map is the character to add to the resulting string.
  5. Repeat steps 3 and 5 for all characters in the strings
  6. Output the string you've built

Here's a block of code using your example with a few more strings:

public static void main(final String[] args) {
    final  StringBuilder stringBuilder = new StringBuilder();

    //Points 1 and 2
    final char[][] characters = new char[][]{
            "where".toCharArray(),
            "wHere".toCharArray(),
            "where".toCharArray(),
            "wperg".toCharArray(),
            "where".toCharArray(),
            "w6ere".toCharArray(),
            "where".toCharArray(),
            "where".toCharArray(),
            "wHere".toCharArray(),
            "w4eeg".toCharArray(),
            "where".toCharArray(),
            "wHare".toCharArray(),
            "where".toCharArray(),
            "where".toCharArray(),
            "weede".toCharArray(),
            "whare".toCharArray(),
            "wHect".toCharArray(),
            "where".toCharArray(),
            "wHere".toCharArray(),
            "whara".toCharArray()
    };

    //Point 3
    for (int i=0; i < 5 ; i++) {

        //Point 4
        final Map<String, Integer> occurrences = new HashMap<String, Integer>();
        for(int j = 0; j < characters.length; j++ ) {

            final String character = ""+characters[j][i];

            if( occurrences.containsKey(character) ) {
                Integer currentTotal = occurrences.get(character);
                occurrences.put(character, ++currentTotal);
                continue;
            }

            occurrences.put(character, 1);
        }

        //Point 5
        int mostOccurrences = 0;
        String characterWithMostOccurrences = "";
        for (final String character : occurrences.keySet()) {
            if( occurrences.get(character) > mostOccurrences ) {
                mostOccurrences = occurrences.get(character);
                characterWithMostOccurrences = character;
            }
        }

        stringBuilder.append(characterWithMostOccurrences);

    }

    //Point 6
    System.out.println(stringBuilder.toString());
}

Here's one I knocked up. It compares the characters in the input strings to check if they are the same in every string in the same position. If the characters in the position match in all input strings, the same character will be in the result string at that position.

public class MultipleStringComparator {

public static void main(String[] args) {

    String[] input = new String[] {"abcdeFgh","abcdefgh","abcdefgh","abcdefgh","abcdefgh"};

    MultipleStringComparator comp = new MultipleStringComparator();
    System.out.println(comp.compare(input, '.'));
}

/**
 * Compare strings character by character
 * @param strings
 * @param substitute - character to insert in result where strings do not match
 * @return result
 */
public String compare(String[] strings, char substitute) {

    //How long is the longest string?
    int longest = 0;
    for (String string : strings) {
        if (string.length()>longest) longest = string.length();
    }

    //Initialise result
    StringBuffer result = new StringBuffer();

    //compare strings character by character
    //If the corresponding characters in all input strings match, append to result
    for (int position=0; position<longest; position++) {
        char character = allCharactersMatch(strings, position);
        if (character!=0) {
            result.append(character);
        } else {
            result.append(substitute);
        }
    }

    return result.toString();
}

/**
 * Compares the character at the specified position in all input strings
 * @param strings
 * @param position
 * @return character found is same in all strings, otherwise 0;
 */
private char allCharactersMatch(String[] strings, int position) {
    char found = 0;
    for (String string : strings) {
        if (string.length()<=position) return 0;
        if (string.charAt(position)!=found && found!=0) return 0;
        found = string.charAt(position);
    }
    return found;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM