IssacZH.
IssacZH.

Reputation: 1477

Efficient way to split an array and organize into multiple array

I got a String[] which contains of multiple user details. Something like this:

Wilson#$20#$Male=@=Raymond#$25#$Male=@=Sophie#$20#$Female

I wanted to split the string up and organize it into multiple array. Such as one array for Name, one array for Age and another array for Gender. Up to this point I managed to split the String[] into something like this.

String[] User = student.split("=@=");

User[0] = Wilson#$20#$Male    
User[1] = Raymond#$25#$Male
User[2] = Sophie#$20#$Female

I don't really know how to organize it from this point. Any comments and answers are highly appreciated!

EDIT

Wilson#$20#$Male=@=Raymond#$25#$Male=@=Sophie#$20#$Female

The above part is actually a value that is returned from the server and I wanted to handle this value. Thank you for all the replies. I think I understand a bit in theory wise, but I'm having slightly issue in implementing codes.

Upvotes: 1

Views: 260

Answers (5)

frIT
frIT

Reputation: 3285

I agree with the suggestions of creating a class for each user - it's the Object Oriented way. So I included it in the example below. But you could probably change it easy enough if you want to do arrays or some other structure.

However, what I want to add is a way to use the Java classes java.util.regex.Pattern and java.util.regex.Matcher to extract both records AND fields in one go from your input string. (I haven't programmed for Android, I assume they are available though.)

The general plan for the pattern is: (record delimiter or nothing)(field1)(delim)(field2)(delim)(lastfield)(record delimiter + rest of input)

The algorithm basically loops through the input with the above pattern. The pattern extracts various groups for the fields (depending on how your record's format) and then also a last group that contains the remainder of the input string. This remainder is used as the new input string for the next loop. So each iteration of the loop does one record.

Here is more complete example code which you can run. You might need to study up on regular expressions to understand the pattern, which is the important part of the algorithm. You can start with the Javadoc for the java.util.regex.Pattern class.

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestPatternMatch {
    public static void main(String[] args) {
        List<User> result = new ArrayList<>();
        String input =
                "Wilson#$20#$Male=@=Raymond#$25#$Male=@=Sophie#$30#$Female";
        Pattern recPatt =
                Pattern.compile("^(=@=|.{0})(.+?)#\\$(\\d+)#\\$(.+?)(?==@=)(.*$)");
        //                       ^match start of line
        //                        ^match record delimiter or nothing
        //                                  ^match name field (reluctant)
        //                                       ^match field delim
        //                                           ^match age field
        //                                                 ^match field delim
        //                                   match gender field^
        // zero-width (non recording) lookahead for record delimiter^
        //                                     match rest of line until end^

        Matcher recMatcher;
        String workStr = input; // start with whole input
        while (workStr != null && workStr.length() > 0) {
            recMatcher = recPatt.matcher(workStr);
            if (recMatcher.matches() && recMatcher.groupCount() >= 5) {
                result.add(
                        new User(
                                recMatcher.group(2), //name
                                Integer.parseInt(recMatcher.group(3)), //age
                                recMatcher.group(4) //gender
                        )
                );
                workStr = recMatcher.group(5); // use tail for next iteration
            } else {
                workStr = null;
            }
        }
        System.out.println(result); //show result list contents
    }
}

class User {
    String  name;
    int     age;
    String  gender;
    /** All argument constructor */
    public User(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    /** Show contents of object fields */
    public String toString() {
        return "User ["+ name + ", " + age + ", " + gender + "]";
    }
}

The basic pattern structure can be reused for many different record formats.

Upvotes: 2

slezadav
slezadav

Reputation: 6141

The best solution would be to create an class User. If you want to avoid it, try:

String[] User = student.split("=@=");
String [][] details=new String[user.length][3];
String [] temp=new String[3];
for(int i=0;i<User.length;i++){
 temp=User.split("//");
  for(j=0;j<3;j++){
  details[i][j]=temp[j];
  }
}

Upvotes: 0

user2030471
user2030471

Reputation:

Why not create a User class and maintain a list of User instances.

class User {

  String name;
  String gender;
  int age;

}

Upvotes: 1

christopher
christopher

Reputation: 27346

Your best bet here, is to use an object to hold these values. Objects are the standardized way to hold values that relate to one another, in one Object. ie:

public class Person
{
    private String name;
    private int age;
    private String gender;
    // Gender could be a boolean value really, but you've stored it as a String.     
}

In the constructor you would request each value and assign it to these fields. It would look something like:

public Person(String name, int age, String gender)
{
    this.name = name; 
    // etc etc
}

That way you have one array, with no need to do any tokenizing of Strings to get to individual values :). You will also need to implement some Accessors and Mutators to get at the values within the Object.

Upvotes: 2

BobTheBuilder
BobTheBuilder

Reputation: 19284

Create a User object to store all fields (name, age, gender) and create a list to hold all data.

Upvotes: 2

Related Questions