Rearranging the position of elements in an array in java?

Okay, this is the first time I go out here, so carry me.

I have a name in the format of "Smith, Bob I" and I need to switch this line to read "Bob I. Smith" . Any ideas on how to do this?

This is one of the ways I've tried, and while it does this work, it looks pretty messy.

 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]); } 
+6
source share
4 answers

If the name is always <last name>, <firstname> , try the following:

 String name = "Smith, Bob I.".replaceAll( "(.*),\\s+(.*)", "$2 $1" ); 

This will put Smith into group 1 and Bob I. into group 2, which will then be referred to as $1 and $2 in the replacement string. Due to the groups (.*) In the expression, the entire line matches and will be completely replaced by a replacement, which is only 2 groups replaced and separated by a white space.

+10
source
  String[] names = "Smith, Bob I.".split("[, ]+"); System.out.println(names[1] + " " + names[2] + " " + names[0]); 
+5
source
 final String[] s = "Smith, Bob I.".split(","); System.out.println(String.format("%s %s", s[1].trim(), s[0])); 
+4
source
 String s = "Smith, Bob I."; String result = s.substring(s.indexOf(" ")).trim() + " " + s.substring(0, s.indexOf(",")); 
+3
source

Source: https://habr.com/ru/post/915436/


All Articles