Home > Enterprise >  Finding the first letter in a String
Finding the first letter in a String

Time:03-15

I have a String

String s="#$% AbcD89";

And I'm trying to get the first letter of that String regardless of if it's capitalized or not. However, I do not know how many characters are before that first letter. I have tried using

int index=0;
outerloop:
for(int i=0; i<s.length;i  ) {
    if(Character.isLetter(s.chartAt(i)) { //Tried with isAlphabetic as well
        index=i;
        break outerloop;
    }
}

But these return what seems to be a random character. Basically, that doesn't return the first letter

Note I cannot use Pattern and Matcher classes

CodePudding user response:

Try it like this. Note that 0 is a legitimate location as an index so initialize your index to -1 and test before using.

String s = "#$% AbcD89";


int index = -1;
for (int i = 0; i < s.length(); i  ) {
    if (Character.isLetter(s.charAt(i))) { 
        index = i;
        break;
    }
}

if (index < 0) {
    System.out.println("No letter found!");
} else {
    System.out.println("First letter is : "   s.charAt(index));
}

prints

First letter is : A 
  • Related