int lastSpace = fullName.lastIndexOf(" ");
这里是所有代码
import java.util.Scanner;
public class java_13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your full name");
String fullName = input.nextLine();
int firstSpace = fullName.indexOf(" ");
String firstName = fullName.substring(0, firstSpace);
int lastSpace = fullName.lastIndexOf(" ");
String lastName = fullName.substring(lastSpace + 1);
System.out.println("\n" + lastName + ", " + firstName);
为什么我们使用(+1) 这里
String lastName = fullName.substring(lastSpace + 1);
答案 0 :(得分:3)
因为空格分割firstName和lastName。
输入应该看起来像" firstName lastName"。如果你采取"的立场"它的空间,然后是" lastName" part从下一个字符开始,因此获取子字符串的位置为+1。
答案 1 :(得分:0)
在Java中,索引以0开头 例如:
String name = "Moataz Mohamed";
name[0]='M';
name[1]='o';
...
name[6]=' '; //Space
空格分隔名字和姓氏。
因此,
0 to index[" "]-1
是名字
index[" "]+1 to length()
是第二个名字
希望现在明白。
答案 2 :(得分:0)
此处全名由名字和姓氏组成,此代码搜索第一个空格以便将名字与姓氏分开 但我建议允许用户同时输入姓氏和名字而不是全名,因为不可能知道组成名字的单词和姓氏相同的单词。
答案 3 :(得分:0)
正如@ 0x01所提到的那样,你得到了空间的索引,但是姓氏是从索引为+1的位置开始的,这就是原因,只需检查这个输出
{...}
public static final String NAME1 = "Julian Papadopulos";
public static final String NAME2 = "John von Bahnhof";
public static final char SPLITCHAR = ' ';
{...}
public static void splitNamesBySpaceIndex() {
// name1
int firstSpace = NAME1.indexOf(" ");
int lastSpace = NAME1.lastIndexOf(" ");
String firstName = NAME1.substring(0, firstSpace);
String lastName = NAME1.substring(lastSpace + 1);
System.out.println("lastname: \'" + lastName + "\', firstname: \'" + firstName + "\'");
lastName = NAME1.substring(lastSpace);
System.out.println("lastname: \'" + lastName + "\', firstname: \'" + firstName + "\'");
}
输出如下:
lastname: 'Papadopulos', firstname: 'Julian'
lastname: ' Papadopulos', firstname: 'Julian'
正如你所看到的,在第二种情况下,你将解析姓氏如' Papadopulos'
,这是不正确的,它是由起始索引引起的空间索引 - 这就是为什么你需要位置索引+1。
答案 4 :(得分:0)
This is like this...
FIRSTNAME LASTNAME
012345678901234567
FIRSTNAME Starts from 0
Index of " " is 9
LASTNAME Starts from 10
That is why you need to add (+1) here
indexOf(" ") {9} but you have to start with LASTNAME which is at 10
If you do not add (+1) then Output will be " LASTNAME"