0

This is my code to find the first non-repeating character and to return its index and the character. How would I get it to only count alphabetical characters?

Thanks for the help :)

// Java program to find first non-repeating character

import java.util.*;
public class GFG 
{ 
    static final int NO_OF_CHARS = 256; 
    static char count[] = new char[NO_OF_CHARS]; 

    /* calculate count of characters 
    in the passed string */
    static void getCharCountArray(String str) 
    { 
        for (int i = 0; i < str.length(); i++) 
            count[str.charAt(i)]++; 
    } 

    /* The method returns index of first non-repeating 
    character in a string. If all characters are repeating 
    then returns -1 */
    static int firstNonRepeating(String str) 
    { 
        getCharCountArray(str); 
        int index = -1, i; 

        for (i = 0; i < str.length(); i++) 
        { 
            if (count[str.charAt(i)] == 1) 
            { 
                index = i; 
                break; 
            } 
        } 

    return index; 
    } 

    // Driver method 
    public static void main (String[] args) 
    { 
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int index = firstNonRepeating(str); 

        System.out.println(index == -1 ? "Either all characters are repeating or string " + 
                "is empty" : "First non-repeating character is " + str.charAt(index)); 
                System.out.println(index);
    } 
} 
Brody2019
  • 67
  • 1
  • 6
  • 1
    Does this answer your question? [What is the best way to tell if a character is a letter or number in Java without using regexes?](https://stackoverflow.com/questions/4047808/what-is-the-best-way-to-tell-if-a-character-is-a-letter-or-number-in-java-withou) – jhamon May 07 '20 at 13:04

1 Answers1

0

With your current code, all you need is this: Once finished, just print the characters with their count. The Character class has other methods to select character types if isAlphabetic is not what you want.

String str = sc.nextLine();
for (char c : str.toCharArray()) {
      if (Character.isAlphabetic(c)) {
              count[c]++;
      }
}
WJS
  • 36,363
  • 4
  • 24
  • 39