indexOf()
andメソッドsubstring()
とcompareTo()
メソッドを使用して、配列内の人の名と姓を入れ替える方法を理解するのに苦労しています。
3 に答える
次のものがあるとします。
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を見て、それを理解できるかどうかを確認してください。
名前がスペースで区切られていることを考慮して、split メソッドを使用して名前を文字列配列に分けることができます。
たとえば、名前を考えてみましょう。
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 メソッドを使用して、分離された姓名を比較できます。
split メソッドによって取得された文字列の 2 つの配列があり、それぞれに 1 つの異なる Person 名があるとします。
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");
}
}
正規表現を使用して、特に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.Comparator
で使用できます。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);
}
これは以下を出力します:
James Bond
John A. Doe
どちらのスニペットでも、名前と姓の境界を定義するために使用されるスペース文字の最後のインデックスであることに注意してください。