Home > Software design >  How do I check for specific characters in a string and return the amount of them?
How do I check for specific characters in a string and return the amount of them?

Time:02-24

so I'm a completely new programmer in Java and I'm trying to figure out how to return the number of lowercase 'e' and uppercase 'E' given user input using JOptionPane.showInputDialog. Here is my current program:

public static void main(String[] args) {
    
    int lowerCaseLetters = 0; // I will use this variable to count 'e'
    int upperCaseLetters = 0; // This variable will be used to count 'E'
    String wordInput; // this is the input for program.
    
    while(true) { // a while loop to continue looping until "STOP" is entered as input
    
    wordInput = JOptionPane.showInputDialog(null, "Please enter a sentence: "); // asking user for input
        for (int i = 0; i < wordInput.length(); i  ) {
            lowerCaseLetters = wordInput.charAt('e');
            if (lowerCaseLetters == 'e')
                lowerCaseLetters  ;
            JOptionPane.showMessageDialog(null, "Number of lower case e's: "  lowerCaseLetters);
            
        }
        if (wordInput.equalsIgnoreCase("stop")) {
            JOptionPane.showMessageDialog(null, "Ending program. "); 
            System.exit(0);
        }
    }
}

}

For example, I'm trying to write the program so that it returns something like this in the JOptionPane.showMessageDialog box when the program asks for input:

Entering the word "Ethereum" would output:

Number of lowercase e's: 2

Number of uppercase E's: 1

and entering a word or sentence with no E's will prompt for user to try again.

CodePudding user response:

You should be able to incorporate the following logic of my count(String, char) method in your Swing app

public class CharacterCount {
    public static void main(String[] args) {
        String text = "How many letters repeat in this sentence? Enter your EXACT guess now."; // 9 lowercase 'e' and 2 uppercase 'E'
        long lowerCaseCount = count(text, 'e');
        long upperCaseCount = count(text, 'E');
        System.out.println("Lower case 'e' count: "   lowerCaseCount);
        System.out.println("Upper case 'E' count: "   upperCaseCount);
    }

    private static long count (String text, char c) {
        return text.chars().filter(ch -> ch == c).count();
    }
}

Using Java streams, you can filter the character stream and count the occurrences of the letter passed in the predicate.

CodePudding user response:

You can use the following method to find out duplicates using HashMap.

 public static void printDuplicateCharacters(String word) {
        char[] characters = word.toCharArray(); // build HashMap with character and number of times they appear in
        Map<Character, Integer> charMap = new HashMap<Character, Integer>();
        for (Character ch : characters) {
            if (charMap.containsKey(ch)) {
                charMap.put(ch,
                        charMap.get(ch)  
                            1);
            } else {
                charMap.put(ch, 1);
            }
        }
        Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
        System.out.printf("List of duplicate characters in String '%s' %n", word);
        for (Map.Entry<Character, Integer> entry : entrySet) {
            if (entry.getValue() > 0) {
                System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
            }
        }
    }

CodePudding user response:

Define your input, and a Map to hold results of analysis. Use a LinkedHashMap to keep keys in the order in which they were inserted.

String input = "Ethereum";
Map < Integer, Integer > mapOfCodePointToOccurrences = new LinkedHashMap <>();

Avoid using the char type. As a 16-bit value, char in incapable of representing most characters. The char type has been essentially broken since Java 2, and legacy since Java 5 when code point related methods were added to various classes.

Instead use code point integer numbers when working with individual characters.

Calling String#codePoints generates an IntStream of code points, a sequence where each element is the code point number for the nth character. Boxing turns the int primitives into Integer objects. Collect those into a List.

List < Integer > codePoints = input.codePoints().boxed().toList();

Determine a distinct list of those code points, eliminating duplicates.

List < Integer > distinctCodePoints = codePoints.stream().distinct().toList();

Loop each of those distinct code points. Search the list of all code points to count occurrences. Put the count into the map.

for ( Integer distinctCodePoint : distinctCodePoints )
{
    long count = codePoints.stream().filter( codePoint -> codePoint == distinctCodePoint ).count();
    mapOfCodePointToOccurrences.put( distinctCodePoint , Math.toIntExact( count ) );
}

Report the results. For each code point key in our map, make a one-character string by calling Character.toString.

// Report
for ( Map.Entry < Integer, Integer > integerIntegerEntry : mapOfCodePointToOccurrences.entrySet() )
{
    String message = "Count of « "   Character.toString( integerIntegerEntry.getKey() )   " » is "   integerIntegerEntry.getValue();
    System.out.println( message );
}

When run:

Count of « E » is 1
Count of « t » is 1
Count of « h » is 1
Count of « e » is 2
Count of « r » is 1
Count of « u » is 1
Count of « m » is 1

Dump other content to console.

System.out.println( "codePoints = "   codePoints );
System.out.println( "distinctCodePoints = "   distinctCodePoints );
System.out.println( "mapOfCodePointToOccurrences = "   mapOfCodePointToOccurrences );

When run:

codePoints = [69, 116, 104, 101, 114, 101, 117, 109]
distinctCodePoints = [69, 116, 104, 101, 114, 117, 109]
mapOfCodePointToOccurrences = {69=1, 116=1, 104=1, 101=2, 114=1, 117=1, 109=1}

As a beginner, you may not yet be comfortable with streams. You can just as well replace the use of streams here with loops. The only exception is the first stream, to get the code points of input. Here is code to transform that first stream into an array of code point integer numbers.

int[] codePoints = input.codePoints().toArray() ;
  •  Tags:  
  • java
  • Related