Home > database >  How to display the index of a letter in a word if it exists?
How to display the index of a letter in a word if it exists?

Time:12-19

First input is a word.

Second input is a letter.

If this letter is in this word, we must print the index of this letter in the word.

Here is my messed code :(

import java.util.Scanner;
public class Main{
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();

        int index=0;
        char ss = in.next().charAt(0);
         for(int i=0; i<str.length(); i  ){
            if(str.charAt(i) == ss){
        System.out.print(str.indexOf(str) " ");
        
    }
    else if(ss!=str.charAt(i)){
        System.out.println("THERE IS NO SUCH LETTER");
        break;
    }
    
    }
        

}
}

CodePudding user response:

You can directly use "str.indexOf(ss) " without loop to print the index of the character.

CodePudding user response:

String#indexOf method returns the index of the first occurrence of the specified character or -1 if the character does not occur.

Refer this post for an example.

  • Related