Home > Software engineering >  Print out the rest of sentence after the first occurrence of the letter in the sentence
Print out the rest of sentence after the first occurrence of the letter in the sentence

Time:01-23

How do I print the rest of the sentence after the first occurrence of the letter in the sentence?

I tried, however, it prints only the sentence and letter I give in the console.

Example: Sentence - How are you? Letter - a O/P: re you?



import java.util.Scanner;

class Program {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);

      System.out.print("Enter a sentence: ");
      String sentence = sc.nextLine();

      System.out.print("Enter a letter: ");
      String letter = sc.next();

      System.out.println(sentence);
      System.out.println(letter);

      // int dec = -1;
      // String str = String.valueOf(dec);

      if (sentence.indexOf(letter) == -1) {
         System.out.println("The letter does not exist in the sentence.");
      } else {
         letter = sentence.substring(sentence.indexOf(letter)   1);
      }

      sc.close();
   }
}

Enter a sentence: hello world Enter a letter: w hello world w The letter does not exist in the sentence.

It not works, it shows given letter does not exist, but in the sentence "w" the letter is present.

CodePudding user response:

The String variable letter is set to the letter you want to find, but then you overwrite it with the resulting sentence. After that, you do nothing with the variable.

You should instead save the result to a different variable, such as sentencePart, then print out that variable. Otherwise your code is confusing to read.

if (sentence.indexOf(letter) == -1) {
    System.out.println("The letter does not exist in the sentence.");
} else {
    String sentencePart = sentence.substring(sentence.indexOf(letter)   1);
    System.out.println("The sentence part is "   sentencePart);
}
  • Related