w3resource
Java Programming Exercies

Java String Exercises: Find first non-repeating character from a stream of characters

Java String: Exercise-49 with Solution

Write a Java program to find first non-repeating character from a stream of characters.

Pictorial Presentation:

Java String Exercises: Find first non-repeating character from a stream of characters

Sample Solution:

Java Code:

import java.util.*;

public class Main {
 final static int MXCHAR = 256;

 static void searchForFirstNonRepChar() {
  List < Character > inDLL = new ArrayList < Character > ();
  boolean[] repeatyn = new boolean[MXCHAR];
  String chrstream = "godisgood";
  System.out.println("String: " + chrstream);
  for (int i = 0; i < chrstream.length(); i++) {
   char x = chrstream.charAt(i);
   System.out.println("Reading: " + x);
   if (!repeatyn[x]) {
    if (!(inDLL.contains(x))) {
     inDLL.add(x);
    } else {
     inDLL.remove((Character) x);
     repeatyn[x] = true;
    }
   }
   if (inDLL.size() != 0) {
    System.out.print("The first non-repeating character so far is:  ");
    System.out.println(inDLL.get(0));
   }
  }
 }

}

Sample Output:

String: godisgood
Reading: g
The first non-repeating character so far is:  g
Reading: o
The first non-repeating character so far is:  g
Reading: d
The first non-repeating character so far is:  g
Reading: i
The first non-repeating character so far is:  g
Reading: s
The first non-repeating character so far is:  g
Reading: g
The first non-repeating character so far is:  o
Reading: o
The first non-repeating character so far is:  d
Reading: o
The first non-repeating character so far is:  d
Reading: d
The first non-repeating character so far is:  i

Flowchart:

Flowchart: Java String Exercises - Find first non-repeating character from a stream of characters

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to remove "b" and "ac" from a given string.
Next: Write a Java program to find lexicographic rank of a given string.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming