gjh
gjh

Reputation: 11

How do I rearrange a string after splitting it in java?

I want to rearrange a name being put in lastname:firstname,middlename so that the o/p is first middle and last. I have it so it splits at the semicolon comma and space.

This is what I have so far:

Scanner n = new Scanner(System.in);

System.out.println("Welcome to the Name Rearranging Program");
System.out.println(" Enter a name in our format:");
// format is lastname:firstname,middlename

String name = n.next();

String[] arr = name.split("[:, ]");

for (int i = 0; i < arr.length; ++i) {
    System.out.println(arr[i]);
}

Upvotes: 0

Views: 1846

Answers (2)

chickenwingpiccolo
chickenwingpiccolo

Reputation: 193

Well I guess I will follow atk's lead and not give away the answer completely but you could also do this using strings rather than arrays. You can do something along these lines:

int colon = name.indexOf(":");
int comma = name.indexOf(",");

From there you can just use string.substring(int beginIndex, int endIndex) with the two above variables to separate each part of the name into its own String and print it out however you wish.

This link talks about substring: http://www.tutorialspoint.com/java/java_string_substring.htm

Upvotes: 0

atk
atk

Reputation: 9314

Since this sounds like homework or another learning exercise, here's a hint to get you on your way. Try adding the following...

String arr = name.split(...);
String last = arr[0];
String first = arr[1];
String middle = arr[2];

This should be enough to make the next step as intuitive as possible.

Upvotes: 3

Related Questions