I would like to know how I can obtain a certain portion of a text string in java, from a word entered by the user. In the code I have, the only options I know of are with substring and subSquence. But for example, if I want to get the last 4 characters of the word that a user enters, since I don't know the number of characters it will have, I couldn't select the position directly. I don't know if there is any way to tell you the number of characters that the word entered by the user has and hence get the last 4 characters. I don't know if I'm explaining myself, I insert the code to make it look clearer.
private static Scanner sc;
private static String pidePalabra() {
System.out.printf("Introduce una palabra de más de 10 caracteres: ");
return sc.nextLine();
}
private static void muestraInfo(String palabra) {
System.out.printf("Primeros 4 caracteres: %s%n", palabra.substring(0,4));
System.out.printf("Del caracter 2 al caracter 8 (ambos incluidos): %s%n", palabra.subSequence(1, 9));
System.out.printf("Últimos 4 caracteres: %s%n");
}
public static void main(String[] args) {
sc = new Scanner (System.in);
String palabra = pidePalabra();
muestraInfo(palabra);
sc.close();
}
}
string.length() : The method
length()
is a final variable that is applied to string objects. The methodlength()
returns the number of characters present in the string.