gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:53:51 25 4
gpt4 key购买 nike

我无法理解如何使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com