Answers for "given a string s, return the first non-repeating character in it and return its index. if it does not exist, return -1."

2

given a string s, return the first non-repeating character in it and return its index. if it does not exist, return -1.

import java.util.Scanner;   
     
public class FirstRepeatedCharacter {
	Scanner in = new Scanner( System.in);     
	public static void main(String[] args)  {
		FirstRepeatedCharacter frc = new FirstRepeatedCharacter();
		frc.mainLoop();
	}
    void mainLoop() {
        String str = " ";
        System.out.println("Please enter a string: ");
        str = in.next();
        str = str.toLowerCase();
        for(int i = 0; i < str.length(); i++) {
            char character = str.charAt(i);
            int firstIndex = str.indexOf(character);
            int lastIndex = str.lastIndexOf(character);
            if(firstIndex != lastIndex) {
                System.out.println("The character '"+character+"' is repeated");
                break; 
            }
        }
    }
}
Posted by: Guest on July-14-2021

Code answers related to "given a string s, return the first non-repeating character in it and return its index. if it does not exist, return -1."

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language