find first non-repeating character in the input string - Java java.lang

Java examples for java.lang:String Algorithm

Description

find first non-repeating character in the input string

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String inputString = "java2s.com";
        System.out.println(getFirstNonRepeatingCharacter(inputString));
    }//from  w  ww  .j a v a  2  s  .c o m

    /**
     * getFirstNonRepeatingCharacter(final String inputString)
     * API to find first non-repeating character in the input string(input is fairly a small string, use getFirstNonRepeatingCharacterFromStream(final String inputString) for StringStream
     * @param inputString
     * @return non-repeating character and if there is none, returns a space character
     */
    public static char getFirstNonRepeatingCharacter(
            final String inputString) {
        int count[] = new int[256];
        char inputChar[] = inputString.toCharArray();
        for (char c : inputChar) {
            count[(int) c]++;
        }

        for (char c : inputChar) {
            if (count[(int) c] == 1) {
                return c;
            }
        }
        return ' ';
    }
}

Related Tutorials