Java programs for string operations (beginner level)
To write a Java program to find the first non-repeating character in a string using basic string operations, without using arrays.
- Read the input string.
- For each character in the string:
- Use
str.charAt(i)
to get the character. - Use
str.indexOf(ch)
andstr.lastIndexOf(ch)
to check if it repeats.
- Use
- The first character where
indexOf == lastIndexOf
is the first non-repeating character. - Display the character.
import java.util.Scanner;
public class FirstNonRepeatingCharNoArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
char firstNonRepeat = '\0'; // default value if no non-repeating char found
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (str.indexOf(ch) == str.lastIndexOf(ch)) {
firstNonRepeat = ch;
break;
}
}
if (firstNonRepeat != '\0') {
System.out.println("First non-repeating character: " + firstNonRepeat);
} else {
System.out.println("No non-repeating character found.");
}
}
}