java - 在 String 类中使用 lastIndexof() 分隔名字和姓氏

标签 java 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("") 

这里只用了“”,但这里取的是完整的字符串。“”是指调用特定字符串方法的完整字符串吗?

最佳答案

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

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

关于java - 在 String 类中使用 lastIndexof() 分隔名字和姓氏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33434910/

相关文章:

r - 从向量中的每个字符串中提取前 N 个字符

bash - 如何在 bash shell 中将一个字符串拆分为至少由一个空格分隔的多个字符串?

java - 如何在 Apache Tomcat 8 中创建子域

java - 正则表达式:匹配并替换字符串中的模式,同时将匹配字符串的一部分保留在替换字符串中

java - 异步NIO : Same client sending multiple messages to Server

Python 替换\\with\

ruby - ruby 中的灵活引号之间有区别吗?

c++ - 我可以从 signed char* 或 unsigned char* 中获取 char* 吗?

java - Mockito - 如何对参数是否在另一个函数调用的函数中设置进行单元测试

java - 闭包编译器 : create_name_map_files from Java API