使用String类中的lastIndexof()分隔firstname和lastname

时间:2015-10-30 11:26:54

标签: java string

我编写了一个代码,用于在名称String:

中分隔名字和姓氏
public class NameSeperator {
    public static void main(String[] args) 
    {
        String custName="Your Name";
        int index;
        String firstName;

        index=custName.indexOf(" ");


        **int last=custName.lastIndexOf("")**;
        firstName=custName.substring(0,index);
        String lastName=custName.substring(index+1,last);

     // get the first name
        System.out.println("First Name = "+firstName);
        System.out.println("Last Name = "+lastName);
    }

} 

我用过

int last=custName.lastIndexOf("") 

仅用于""这里需要完整的字符串。这是""是指调用特定字符串方法的完整字符串?

3 个答案:

答案 0 :(得分:3)

您可以按空格直接拆分,然后使用数组索引

String name[] = custName.split(" ");
String firstName = name[0];
String lastName = name[1]

答案 1 :(得分:2)

我会推荐这个简化版本:

int index = custName.indexOf(' ');
String firstName = custName.substring(0, index);
String lastName = custName.substring(index + 1);

请注意indexOf搜索单个字符。此外,lastName的第二个子字符串会将剩余的字符串直到结束。

答案 2 :(得分:0)

修改您的代码:

  String custName="Your Name";

  int start = custName.indexOf(' ');
  int end = custName.lastIndexOf(' ');

  String firstName = "";
  String middleName = "";
  String lastName = "";

  if (start >= 0) {
      firstName = custName.substring(0, start);
      if (end > start)
          middleName = custName.substring(start + 1, end);
      lastName = custName.substring(end + 1, custName.length());
  }     

  System.out.println("First Name = "+firstName);
  System.out.println("Middle Name = "+middleName);
  System.out.println("Last Name = "+lastName);