简体   繁体   中英

Last two letters of a user inputted string using substring (Java)

I'm writing a program that generates star wars names. The user inputs their first, last, mother's maiden name, birth city, and first car and the program gives a star wars name. I need the last two characters* of the user inputted last name. I know I can use substring , but I cannot get anything to work. The best I have is:

lastname.substring(lastname.length() -2)

which gives the first two letters of the last name, and not the last. Also, I cannot use lastname.substr(-2) because substr for some reason won't work (not sure why, this would be much easier).

Thanks for any help.

*EDIT: I hope I didn't confuse anyone, I need the last two characters of the last name.

Actually I see my problem now: my original last name variable is

String lastname = console.nextLine().substring(0,2).trim().toUpperCase();

which keeps the first two letters, so the reason I was getting the first two letters was because of this. I understand now. Is there a way to get the last two letters from this same variable?

So if the name was Michael , you just want Micha ?

Try:

String trimmedLastName = lastName.substring(0, lastName.length() - 2);

For example:

String lastName = "Michael";
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
System.out.println(trimmedLastName); // prints Micha

The reason mine works and yours doesn't is because the first parameter of substring is where to start . So I start from the first letter, and end on the second last letter (not inclusive).

What yours does is start on the second last letter, and continue on until the end of the string.


However, if you wanted just el from Michael , you could do this:

String lastName = "Michael";
String trimmedLastName = lastName.substring(lastName.length() - 2);
System.out.println(trimmedLastName); // prints el

试试看

lastname.substring(lastname.length() -3,lastname.length() -1);

If you need the different ways, here:

StringBuffer myString = new StringBuffer(inputString);
myString.revert();

StringBuffer userInput = new StringBuffer(myString.subString(2));

String result = userInput.revert();

Have a nice day.

lastname.substring(lastname.length() - 2) should return the last 2 letters.

lastname.substring(0, 2) returns the first two.

substring(index) is includive

substring(index1, index2) is inclusive, exclusive respectively.

Because String is immutable so when you call subString it doesn't change the value of lastname.

I think you should do: String genName = lastname.subString(lastname.lengh()-2);

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