java - 使用indexOf和substring以及compareTo交换名称

标签 java string swap

我无法理解如何使用 indexOf()substring()compareTo() 方法来翻转人们的名字将他们的姓氏放在数组中。

最佳答案

假设您有以下内容:

String[] names = new String[]{"Joe Bloggs", "Sam Sunday"};

您可以使用以下代码交换姓氏和名字:

for (int i=0; i < names.length; i++)
{
    String someName = names[i];
    int spaceBetweenFirstAndLastName = someName.indexOf(" ");
    //These next two lines of code may be off by a character
    //Grab the characters starting at position 0 in the String up to but not including
    //   the index of the space between first and last name
    String firstName = someName.substring(0, spaceBetweenFirstAndLastName);
    //Grab all the characters, but start at the character after the space and go 
    //   until the end of the string
    String lastName = someName.substring(spaceBetweenFirstAndLastName+1);
    //Now, swap the first and last name and put it back into the array
    names[i] = lastName + ", " + firstName;
}

字符串 compareTo 方法现在可用于通过将一个名称与另一个名称进行比较来对名称进行排序,因为姓氏是字符串的开头。看看api here看看你是否能弄清楚。

关于java - 使用indexOf和substring以及compareTo交换名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2740136/

相关文章:

java - Eclipse 是否有排列类文件的功能?

python - 子类 string.Formatter

c++ - 以可变大小作为参数的二维数组 C++

Android用动画交换两个图像

java - 如何合并两个具有相同参数的XML文件?

java - 在 Java 的 While 循环之外传递结果集

objective-c - 如何拆分一串单词并添加到数组中 - Objective C

c - 在c中交换字符串

java - 如何以简约的方式处理 "Calling home"?

ios - 如何在斜杠之间获取字符串 -Swift