Finding the First Non-Repeating Character in a String in Java

06 May 2023 Balmiki Mandal 0 Core Java

Find the First Non Repeating Character in a String in Java

When it comes to solving string problems, Java provides plenty of useful methods that can help you with your task. One of the most common string problems is finding the first non-repeating character in a string. This article will provide a step-by-step guide on how to do this in Java.

Steps for Finding the First Non-Repeating Character in a String

  1. Use a for loop to iterate through each character in the string.
  2. For each character, use another for loop to iterate through the rest of the characters and check if the current character is present more than once.
  3. If the character appears only once, you have found the first non-repeating character.
  4. If not, continue until the end of the string.

Java Example

Now let's look at an example of how to do this in Java. We will be using a for loop and two counters to keep track. The first counter 'i' will be our main counter for looping through the string. The second counter 'j' will loop through the remaining characters of the string when we come upon a unique character. Here is the code:

public static char firstNonRepeatingChar(String s) {
  int[] count = new int[256];
  char[] cArray = s.toCharArray();
  // Loop through each character in the string
  for (int i=0; i<cArray.length; i++) {
    count[cArray[i]]++;  // Increment the count in the count array 
  }
  // Loop through the string again
  for (int i=0; i<cArray.length; i++) {
    if (count[cArray[i]] == 1) {  // Check if count is 1
      return cArray[i];  // Return the first non-repeating character
    }
  }
  return 0;  // Return 0 if no non-repeating character is found
}

Conclusion

In this article, we looked at how to find the first non-repeating character in a string in Java. We went over a step-by-step guide and an example of how to do this using a for loop and two counters. Hopefully you now have a much better understanding of how to solve this problem and can apply it to your own projects. Good luck!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.