BM Balmiki Mandal 06 May 2023 16 views 0 comments Core Java

Finding the First Non-Repeating Character in a String in 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!

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023