简体   繁体   中英

Finding the second last occurence character in a string

this is my code, where i am just reversing the loop and then increasing the counter such that for the first occurrence the count value is 1 and hence skips the println() case. After this, in the second occurrence it will go to the nested if case and just print the index of the second last vowel.

  class Main {
      public static void main(String[] args) {
        int count=0;
        String str = "corresponding";
        for(int i=str.length();i>=0;i--){
          if(i=='a' || i=='e' ||i =='i'|| i=='o'|| i=='u'){
            count +=1;
            if(count==2)
              System.out.println(i);
            else
            continue;
          }
          else
            continue;
        }
      }
    }

I am not able to print due to some minor logical error which i am not able to figure out. Can anyone help me here.

You are comparing i to the vowel character instead of comparing the character from the String, so you should do this:

char c = str.charAt(i);
if (c=='a' || c=='e' ||c =='i'|| c=='o'|| c=='u')

Please also take note that i should start from str.length()-1

To begin, you should heed the starting index which throws an exception as you access elements of the array. You don't get the error just for now since you don't access the elements. Let's try to access them by using the charAt method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM