用户使用子字符串(Java)输入的字符串的最后两个字母 [英] Last two letters of a user inputted string using substring (Java)

查看:52
本文介绍了用户使用子字符串(Java)输入的字符串的最后两个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个生成星球大战名称的程序.用户输入他们的名字、姓氏、母亲的娘家姓、出生城市和第一辆车,程序会给出一个星球大战的名字.我需要用户输入姓氏的最后两个字符*.我知道我可以使用 substring,但我无法使用任何东西.我拥有的最好的是:

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)

给出姓氏的前两个字母,而不是最后一个.另外,我不能使用 lastname.substr(-2) 因为 substr 由于某种原因不起作用(不知道为什么,这会容易得多).

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

感谢您的帮助.

*我希望我没有混淆任何人,我需要姓氏的最后两个字符.

* 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?

推荐答案

那么如果名字是Michael,你只想要Micha?

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

试试:

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

例如:

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

我的工作和你的不工作的原因是因为 substring开始的地方.所以我从第一个字母开始,到倒数第二个字母(不包括)结束.

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.

然而,如果你只想要 Michaelel,你可以这样做:

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

这篇关于用户使用子字符串(Java)输入的字符串的最后两个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆