Question: how to find the first non-repeated character in a String?
The below Java program has been optimised and written easy for understanding.
The below Java program has been optimised and written easy for understanding.
import java.util.Scanner;
public class StrRepeat {
public static void main(String args[]){
//Get the string to check the non repreated character
System.out.println("Enter the String: ");
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char fin = checkLetter(str);
System.out.println("The character is: " + fin);
s.close();
}
//To check each individual char for non repeated
private static char checkLetter(String str) {
// TODO Auto-generated method stub
//To split the string to character
char[] ary = str.toCharArray();
char val = 0;
//To get the length of character
int len = ary.length;
char temp[] = new char[len];
for (int i=0; i<len; i++){
for (int j=0; j<len; j++){
if (j!= i){
if(ary[i] == ary[j]){
temp[i] = '$';
}
}
}
}
for (int k = 0; k< len; k++){
if (temp[k] != '$' ){
val = ary[k];
break;
}
}
return val;
}
}
Output:
Enter the String: madam
The character is: d
No comments:
Post a Comment