How to know if the first character of a String is an int?

0

My problem as the title indicates I want to know if the first character of a String is a number 9. I have the following code but I want to know if it can be optimized:

String palabra = "9394";
if(palabra != null && palabra.contains("9")){
    int index = palabra.indexOf("9");
    if(index == 0){
         System.out.println("9 es la primera letra");
    }
}
    
asked by J. Castro 20.03.2018 в 20:25
source

2 answers

5

You can use string.charAt(0) that allows you to get the first character of the string.

if (string.charAt(0) = '9') {
// Tu codigo
}
  

.charAt(index) Remember that it returns a char type.

Additional Information : if you want to know if the first character is a digit, it does not matter which (not only 0 to 9, all of the unicode):

Character.isDigit(string.charAt(0))
    
answered by 20.03.2018 / 20:35
source
2

There are several ways to do what you want. Perhaps the simplest thing to do is to use substring , since apparently it does not interest a conversion of types, but only to verify that the first character is 9 or not.

I show you an example, also using a ternary operator, which can be very useful for these cases, helping to simplify code.

    String palabra = "9394";
    String laPrimera=palabra.substring(0, 1);
    String esNueve=(palabra != null && laPrimera.equals("9")) ? "Es nueve: " : "No es nueve, es: ";
    System.out.println(esNueve+laPrimera);

Exit:

Es nueve: 9

If we try for example with this value: "1394" , the output would be:

No es nueve, es: 1
    
answered by 20.03.2018 в 21:09