Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);


    }
like image 799
Lambda Avatar asked May 10 '12 20:05

Lambda


People also ask

How do you change positions in an array Java?

Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.

How do you switch position elements in an array?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.

Can we swap elements in array?

In an array, we can swap variables from two different locations. There are innumerable ways to swap elements in an array. let's demonstrate a few ways of swapping elements. We introduce a new variable and let it hold one of the two array values(a) which are willing to swap.

How do you shift an element to the left in an array Java?

If an array consists of elements arr = {1, 2, 3}, then on shifting these elements towards the left direction by one we would get arr = {2, 3, 1}. Example 2: If an array consists of elements arr = {20, 30, 10, 40}, then on shifting these elements towards the left direction by three we would get arr = {40, 20, 30, 10}.


1 Answers

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.

like image 169
Thomas Avatar answered Sep 27 '22 23:09

Thomas