Skip to content

sharan-maker/Java-Assignments-String-operations-

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

Java-Assignments-String-operations-

Java programs for string operations (beginner level)

Java Assignment: First Non-Repeating Character (No Arrays)

Aim

To write a Java program to find the first non-repeating character in a string using basic string operations, without using arrays.

Algorithm

  1. Read the input string.
  2. For each character in the string:
    • Use str.charAt(i) to get the character.
    • Use str.indexOf(ch) and str.lastIndexOf(ch) to check if it repeats.
  3. The first character where indexOf == lastIndexOf is the first non-repeating character.
  4. Display the character.

Program

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.");
        }
    }
}

About

Java programs for string operations (beginner level)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages