0

I've got a simple problem, but I'm new to Java coming from PHP. I need to split a delimited text file into an array. I've broken it down into an array of lines, each one would look something like this:

{
    {Bob | Smithers | Likes Cats | Doesnt Like Dogs},
    {Jane | Haversham | Likes Bats | Doesnt Like People}
}

I need to turn this into a 2 dimensional array.

In PHP, it's a cinch. You just use explode(); I tried using String.split on a 1d array and it wasn't that bad either. The things is, I haven't yet learned how to be nice to Java. So I don't know how to loop through the array and turn it into a 2d. This is what I have:

for (i = 0; i < array.length; i++) {
    String[i][] 2dArray = array[i].split("|", 4);
}

PHP would be

for ($i = 0; $i < count($array); $i++) {
    $array[i][] = explode(",", $array[i]);
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Cookie
  • 21
  • 2
  • What error are you getting when you do this? And why do you limit your result to '4'? – matt May 23 '18 at 12:16
  • Possibly related: [Splitting a Java String by the pipe symbol using split(“|”)](https://stackoverflow.com/q/10796160) – Pshemo May 23 '18 at 12:16
  • You don't "turn array into 2d array". You read first array and write each item from it to array of its own that you also need to save somewhere. Since you allegedly already got one array from a string, what's stopping you from getting array from each string in that array? – M. Prokhorov May 23 '18 at 12:22
  • M Prokhorov... my ignorance is stopping me. Pshemo I got something that said @CheckReturnValue – Cookie May 23 '18 at 12:29
  • Can you give some example input and the desired output? Not only the structure of your partial result. – Zabuzard May 23 '18 at 12:31
  • Pshemo, the pipe symbol was just an example. It's not compiling. – Cookie May 23 '18 at 12:31
  • 1
    Also, it would help if you add the PHP code as reference. Than it's easier to understand what exactly you want to achieve. – Zabuzard May 23 '18 at 12:33
  • @Cookie, when asking a question, you should give exactly what you want, and exactly what you did and what went wrong. I see that your code would not compile, but I know that from experience (your declaration for 2d array type is wrong). – M. Prokhorov May 23 '18 at 12:35
  • Zabuza, I'm on it. – Cookie May 23 '18 at 12:39
  • When you assign the elements of 2dArray, you just do `2dArray[i] = array[i].splitj("\\|");` – matt May 23 '18 at 12:41
  • Hello. Since you are new on Stack Overflow you may not know yet that it is good to use `@nickOfPerson` if you are responding to that person's comment. This way that person will be notified about your response. Anyway lets go back to: "*the pipe symbol was just an example*", OK but code you posted was also based on that example and had problem related to splitting on `|` which is why I posted my comment (to avoid such situations lets try not to introduce problems unrelated to real question). – Pshemo May 23 '18 at 12:48

2 Answers2

0

You can loop the array like this:

    // Initialize array
    String[] array = {
            "Bob | Smithers | Likes Cats | Doesnt Like Dogs",
            "Jane | Haversham | Likes Bats | Doesnt Like People"
    };

    // Convert 1d to 2d array
    String[][] array2d = new String[2][4];
    for(int i=0;i<array.length;i++) {
        String[] temp = array[i].split(" \\| ");

        for(int j=0;j<temp.length;j++) {
            array2d[i][j] = temp[j];
        }
    }

    // Print the array
    for(int i=0;i<array2d.length;i++) {
        System.out.println(Arrays.toString(array2d[i]));
    }

Notes: I used \\|to split the pipe character.

Triando
  • 1
  • 1
0

Problem

If I got you right you have an input like this:

{{Bob | Smithers | Likes Cats | Doesnt Like Dogs},{Jane | Haversham | Likes Bats | Doesnt Like People}}

Readable version:

{
    {Bob | Smithers | Likes Cats | Doesnt Like Dogs},
    {Jane | Haversham | Likes Bats | Doesnt Like People}
}

And you want to represent that structure in a 2-dimensional String aray, String[][].


Solution

The key is the method String#split which splits a given String into substrings delimited by a given symbol. This is , and | in your example.

First of all we remove all {, } as we don't need them (as long as the text itself does not contain delimiter):

String input = ...
String inputWithoutCurly = input.replaceAll("[{}]", "");

The text is now:

Bob | Smithers | Likes Cats | Doesnt Like Dogs,Jane | Haversham | Likes Bats | Doesnt Like People

Next we want to create the outer dimension of the array, that is split by ,:

String[] entries = inputWithoutCurly.split(",");

Structure now is:

[
    "Bob | Smithers | Likes Cats | Doesnt Like Dogs",
    "Jane | Haversham | Likes Bats | Doesnt Like People"
]

We now want to split each of the inner texts into their components. We therefore iterate all entries, split them by | and collect them to the result:

// Declaring a new 2-dim array with unknown inner dimension
String[][] result = new String[entries.length][];

// Iterating all entries
for (int i = 0; i < entries.length; i++) {
    String[] data = entries[i].split(" | ");

    // Collect data to result
    result[i] = data;
}

Finally we have the desired structure of:

[
    [ "Bob", "Smithers", "Likes Cats", "Doesnt Like Dogs" ],
    [ "Jane", "Haversham", "Likes Bats", "Doesnt Like People"]
]

Everything compact:

String[] entries = input.replaceAll("[{}]", "").split(",");
String[][] result = new String[entries.length][];

for (int i = 0; i < entries.length; i++) {
    result[i] = entries[i].split(" | ");
}

Stream

If you have Java 8 or newer you can use the Stream API for a compact functional style:

String[][] result = Arrays.stream(input.replaceAll("[{}]", "").split(","))
    .map(entry -> entry.split(" | "))
    .toArray(String[][]::new);
Zabuzard
  • 25,064
  • 8
  • 58
  • 82