SANDEEP RAO
SANDEEP RAO

Reputation: 13

How to print a Letter between two vowels using java

I Have a String S= "I love bangalore " It should print the letters between 2 vowels like below : 1.v 2.ng 3.l 4.r

Note : I am able to print if there only 1 letter b/w 2 vowels not more than that.

This what I have tried :

String a = "i love bangalore";

String[] words = a.split(" ");
for (String word : words) {
    for (int i = 1; i < word.length(); i++) {
        if (word.length() > 3) {
          if(i==word.length()-1){
              System.out.println("skip");
          }
          else if(checkIsVowel(word.charAt(i))&&!checkIsVowel(word.charAt(i+1))&&checkIsVowel(word.charAt(i+2))){
              System.out.println(word.charAt(i+1));
              }

          }
        }
    }

Upvotes: 1

Views: 269

Answers (2)

WJS
WJS

Reputation: 40034

The best way to do this is as follows:

  1. Find a vowel, non-vowel pair.
  2. Set result to non-vowel.
  3. Continue to find non-vowels, appending to result
  4. When a vowel is encountered, either print or save result
  5. remembering you are at a vowel, go back to 1 and repeat until word is exhausted.

Make certain you use print statements to help debug your program.

Upvotes: 0

Sunil Dabburi
Sunil Dabburi

Reputation: 1472

The way you are trying is not right because

  1. You are checking for length 3 or more which is not true
  2. You are checking for vowel, normal alphabet, vowel which is also not true. ex: angl

Here is one way to solve it

String[] words = str.split(" ");
for (String word : words) {
    int firstVowelIndex = -1;
    for (int i = 0; i < word.length(); i++) {
        char ch = word.charAt(i);
        if (checkIsVowel(ch)) {
            // if vowel index is found again and there exists at least one character between the two vowels
            if (firstVowelIndex != -1 && i - firstVowelIndex != 0) {
                System.out.println(word.substring(firstVowelIndex + 1, i));
            }
            // vowel index is assigned
            firstVowelIndex = i;
        }
    }
}

Input:

i love bangalore

Output:

v
ng
l
r

Upvotes: 1

Related Questions