Java program to return the first non repeated character in a string

This post is about java program to return the first non repeated character in a string.

Example:
Given a string "hhello", It should return 'e' as the first non repeated character.

Logic of the program:
Using a linked hash map will solve this program.

  • All the characters[a-z] can be stored in a linked hash map as key and value should be corresponding to be number of occurrence of each character. 
  • To return the first non repeated char, just iterate the linked hash map and return first key having value as 1.

Program:

package com.techjourney;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Sujith Mohan on 6/4/2015.
 */
public class FirstNonRepeatedChar {
    public static char returnFirstNonRepeatedChar(String str)
    {
        if(str==null)
            throw new NullPointerException();
        if(str.equals(""))
            return '\0';

        LinkedHashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();

        //converting the string to lowercase and trimming all zeros
        String str_lc = str.toLowerCase();
        str_lc = str_lc.replaceAll("[^a-zA-Z]+", "");

        for(int i=0;i<str_lc.length();i++)
        {
            char gets = str_lc.charAt(i);
            if(map.containsKey(gets))
            {
                int count = map.get(gets);
                map.put(gets,++count);
            }
            else
            {
                map.put(gets, 1);
            }
        }

        //iterating the map
        for(Map.Entry<Character, Integer> entry: map.entrySet())
        {
            char key = entry.getKey();
            if(entry.getValue()==1)
            {
                return key;
            }
        }
        return '\0';

    }

}

Test cases:

package com.techjourney;

import static org.junit.Assert.*;

import org.junit.Test;

/**
 * Created by Sujith Mohan on 6/4/2015.
 */
public class FirstNonRepeatedCharTest {
    @Test
    public void testForFirstNonRepeatedChar() {
        assertEquals('t', FirstNonRepeatedChar.returnFirstNonRepeatedChar("Techjourney"));

        //test case with a special character
        assertEquals('d', FirstNonRepeatedChar.returnFirstNonRepeatedChar("#aAbBcCdeEfF"));

        //test case with no non repeated characters
        assertEquals('\0', FirstNonRepeatedChar.returnFirstNonRepeatedChar("Techjourney techjourney"));

        //test case with empty string
        assertEquals('\0', FirstNonRepeatedChar.returnFirstNonRepeatedChar(""));

    }

    @Test(expected = NullPointerException.class)
    public void testForException() throws NullPointerException
    {
        //test case throwing exception
        FirstNonRepeatedChar.returnFirstNonRepeatedChar(null);
    }

}

All the test cases were passed successfully.





















The same logic can be used for printing number of occurrence of each character in a String and other similar programs.

Other posts in this blog:

  1. Java program to get details about memory.
  2. Correct way to create and populate suggestbox in GWT.
  3. Program to check big-endian or little-endian.


Comments

  1. I was very encouraged to find this site. I wanted to thank you for this special read.

    ReplyDelete

Post a Comment

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++