Swapping the position of elements within an array in java?
题
Ok, so it's the first time I am posting out here, so bear with me.
I have a name in the format of "Smith, Bob I"
and I need to switch this string around to read "Bob I. Smith"
. Any ideas on how to go about doing this?
This is one way that I've tried, and while it does get the job done, It looks pretty sloppy.
public static void main(String[] args) {
String s = "Smith, Bob I.", r = "";
String[] names;
for(int i =0; i < s.length(); i++){
if(s.indexOf(',') != -1){
if(s.charAt(i) != ',')
r += s.charAt(i);
}
}
names = r.split(" ");
for(int i = 0; i < names.length; i++){
}
System.out.println(names[1] +" " + names[2] + " " + names[0]);
}
解决方案
If the name is always <last name>, <firstname>
, try this:
String name = "Smith, Bob I.".replaceAll( "(.*),\\s+(.*)", "$2 $1" );
This will collect Smith
into group 1 and Bob I.
into group 2, which then are accessed as $1
and $2
in the replacement string. Due to the (.*)
groups in the expression the entire string matches and will be replaced completely by the replacement, which is just the 2 groups swapped and separated by a space character.
其他提示
String[] names = "Smith, Bob I.".split("[, ]+");
System.out.println(names[1] + " " + names[2] + " " + names[0]);
final String[] s = "Smith, Bob I.".split(",");
System.out.println(String.format("%s %s", s[1].trim(), s[0]));
String s = "Smith, Bob I.";
String result = s.substring(s.indexOf(" ")).trim() + " "
+ s.substring(0, s.indexOf(","));
不隶属于 StackOverflow