Capture the last character of a name

0

How to capture the last letter of a name (Juan Pedro) but I do not know how I could do it, I am new in this programming and I would appreciate if you could help me.

String nombre="Juan Pedro";
int cantidad=nombre.length();
String nomMay=nombre.toUpperCase();
String nomMin=nombre.toLowerCase();
char letraUno=nombre.charAt(0);
char letraDos=nombre.charAt(1);
System.out.println("Cantidad de letras: "+cantidad);
System.out.println("Mayusculas: "+nomMay);
System.out.println("Minusculas: "+nomMin);
System.out.println("Primera letra: "+letraUno);
System.out.println("Segunda letra: "+letraDos);
String a="";
String d=a+letraUno+letraDos;
System.out.println(d);
    
asked by Franco Zaconetta Gosicha 01.05.2017 в 18:55
source

3 answers

0

It can be done using the charAt , donde la posición será el length de la cadena -1 .

char ultimo = nombre.charAt(nombre.length()-1);
System.out.println(ultimo);

Or with the method substring going through the same parameter as charAt , with the difference that substring returns a String and < a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#charAt-int-"> charAt a carácter .

String ultimo = nombre.substring(nombre.length() - 1);
System.out.println(ultimo);
    
answered by 01.05.2017 / 19:02
source
1

The last position of a string is obtained in the form:

int posFinal = nombre.length()-1; //Restas uno para obtener el índice del ultimo caracter
char caracterFinal = nombre.charAt(posFinal);//obtienes el carácter de dicha posición
    
answered by 01.05.2017 в 20:55
0
  

A String in Java is a string of concatenated characters. These characters have a certain order

Example: The string " home " is the set of characters:

C -> Primer caracter
A -> ...
S -> ...
A -> Último caracter

The order they follow starts from 0, until the last character, which is length () - 1 , where length () is the total number of characters it contains ("house" has 4)

Therefore, the "home" String looks like this:

C -> 0
A -> 1
S -> 2
A -> 3
  

To traverse a String by storing each character in a variable, the most common is to use the for loop and the charAt (int n) method, which returns the character that takes the place n :

String palabra = "casa";
char letra;
for (int i = 0; i < palabra.length(); i++) {
    // Almacenamos cada caracter en la variable
    letra = palabra.charAt(i);
}

Therefore, to get the last character:

char ultimo = palabra.charAt(palabra.length() - 1);

Documentation

    
answered by 02.05.2017 в 20:05