user125347
user125347

Reputation: 113

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?

Upvotes: 1

Views: 3674

Answers (5)

LINEMAN78
LINEMAN78

Reputation: 2562

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.

Upvotes: 0

Michael Yaworski
Michael Yaworski

Reputation: 13483

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

Upvotes: 4

SangDang
SangDang

Reputation: 11

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);

Upvotes: 0

Thanh Le
Thanh Le

Reputation: 773

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.

Upvotes: 0

Dark Knight
Dark Knight

Reputation: 8357

Try this out,

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

Upvotes: 0

Related Questions