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

发布于 2024-08-30 09:55:25 字数 115 浏览 6 评论 0原文

我无法理解如何使用 indexOf()substring() 以及 compareTo() 方法来翻转人们的名字和姓氏数组中的名称。

I am having trouble understanding how to use the indexOf() and substring() and compareTo() methods to flip people's first name with their last name in an array.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

dawn曙光 2024-09-06 09:55:25

假设您有以下内容:

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 此处 看看你是否能弄清楚。

Let's say you have the following:

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

You can use the following code to swap the last name and first name:

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;
}

The string compareTo method can now be used to sort the names by comparing one name against another, now that the last name is the start of the string. Have a look at the api here and see if you can figure it out.

み格子的夏天 2024-09-06 09:55:25

您可以使用 split 方法将名称分隔到 String 数组中,考虑到它们是用空格分隔的。

例如,让我们考虑一个名称:

String name = "Mario Freitas";

String[] array = name.split(" "); // the parameter is the string separator. In this case, is the space

for(String s : array){
    System.out.println(s);
}

此代码将在不同的行中打印每个名称(因为字符串是分隔的)

然后您可以使用 equals 方法比较分隔的名字和姓氏。

假设您有 2 个字符串数组,通过 split 方法获得,每个数组都有一个不同的人名。

public void compare names(String name1, String name2){
    String array1[] = name1.split(" ");
    String array2[] = name2.split(" ");

    if(array1[0].equals(array2[0])){
        System.out.println("First names are equal");
    }

    if(array1[1].equals(array2[1])){
        System.out.println("Second names are equal");
    }
}

Yo can use the split method to separate the names into a String array, considering that they are separed by a space.

For example, lets consider a name:

String name = "Mario Freitas";

String[] array = name.split(" "); // the parameter is the string separator. In this case, is the space

for(String s : array){
    System.out.println(s);
}

this code will print each name in a different line (as the String was separated)

Then you can compare the first and last name separated, using the equals method.

Let's suppose you have 2 array of Strings, obtained by split method and each one with one different Person name.

public void compare names(String name1, String name2){
    String array1[] = name1.split(" ");
    String array2[] = name2.split(" ");

    if(array1[0].equals(array2[0])){
        System.out.println("First names are equal");
    }

    if(array1[1].equals(array2[1])){
        System.out.println("Second names are equal");
    }
}
海之角 2024-09-06 09:55:25

您可以使用正则表达式,特别是 String.replaceAll(String regex, String replacement) 对名字和姓氏重新排序。

    String[] names = { "John A. Doe", "James Bond" };
    for (int i = 0; i < names.length; i++) {
        names[i] = names[i].replaceAll("(.*) (.*)", "$2, $1");
        System.out.println(names[i]);
    }

这将打印:

Doe, John A.
Bond, James

但是,如果您交换的唯一原因是因为您稍后想要对姓氏进行排序,那么您实际上根本不需要交换。只需将姓氏提取代码封装到辅助方法中(因此它是可测试的、可重用的等),然后在您的自定义 java.util.Comparatorjava.util.Arrays.sort

import java.util.*;

//...

static String lastName(String name) {
    return name.substring(name.lastIndexOf(' '));
}

//...

String[] names = { "John A. Doe", "James Bond" };       
Comparator<String> lastNameComparator = new Comparator<String>() {
    @Override public int compare(String name1, String name2) {
        return lastName(name1).compareTo(lastName(name2));
    }           
};
Arrays.sort(names, lastNameComparator);
for (String name : names) {
    System.out.println(name);
}

打印:

James Bond
John A. Doe

请注意,在这两个片段中,空格字符的 last 索引用于定义名字和姓氏之间的边界。

You can use regular expressions, specifically String.replaceAll(String regex, String replacement) to reorder the first name and last name.

    String[] names = { "John A. Doe", "James Bond" };
    for (int i = 0; i < names.length; i++) {
        names[i] = names[i].replaceAll("(.*) (.*)", "$2, $1");
        System.out.println(names[i]);
    }

This prints:

Doe, John A.
Bond, James

However, if the only reason why you're swapping is because you later want to sort on last names, then you actually don't need to swap at all. Just encapsulate the last name extracting code into a helper method (so it's testable, reusable, etc), and then use it in your custom java.util.Comparator for java.util.Arrays.sort

import java.util.*;

//...

static String lastName(String name) {
    return name.substring(name.lastIndexOf(' '));
}

//...

String[] names = { "John A. Doe", "James Bond" };       
Comparator<String> lastNameComparator = new Comparator<String>() {
    @Override public int compare(String name1, String name2) {
        return lastName(name1).compareTo(lastName(name2));
    }           
};
Arrays.sort(names, lastNameComparator);
for (String name : names) {
    System.out.println(name);
}

This prints:

James Bond
John A. Doe

Note that in both snippets, it's the last index of the space character that is used to define the boundary between the first and last name.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文