1

For my program, the input from the user will be something like this:

{1,2,3} {1,2} {4,5,6}

There can be multiple { } with any number of ... numbers inside.

I already made a 2 dimensional array with an array for each sequence of numbers: {}

I am having troubling splitting them into their respective arrays so it will be something like this:

Array[0] = ["1","2","3"]    
Array[1] = ["1","2"]  
Array[2] = ["4","5","6"]  

How would i split it like that? i dont know if i can split this string into n number of strings since the number of sequences depends on user.

4 Answers 4

3

Split the string on " " (space), and from there remove the curly brackets (perhaps take a substring, from index 1 to index length-1). Then split on comma. That should return a string array containing numbers. From there parse the strings to integers, and store in an integer array.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah this seems to work. I made another array to hold each sequence as an element before sorting them again (which is easier now). Thanks :)
0

This code will help you

public class T {
    public static void main(String[] args) {

        String s = "{1,2,3} {1,2} {4,5,6}";

        String[] mainArray = s.split(" ");
        String[][] result = new String[mainArray.length][];
        int count = 0;
        for (String t : mainArray) {
            result[count] = t.split(",");
            count++;
        }

    }
}

Comments

0
var x = "{1,2,3} {1,2} {4,5,6}"; 
var y = x.split(" ");
var k =[];
for(var i = 0; i < y.length; i++){
    k.push((y[i].substring(1,y[i].length-1)).split(","));
} 

Well, this be how you would do it in javascript, algorithm.(my bad mis-read the tag) K will be the final array.

Comments

0

Create a collection of arrays (of the type the input arrays will be, if known). Split the array on "{". With the resulting array, you remove the "}" from each string and split it on ",". Then iterate over the resulting string array, parsing its contents and building an array of your entry type. Finally, add that array to your collection.

This assumes there are no sub-arrays, true for your sample input. It does not assume the user added spaces between the given arrays, however; that is something I wouldn't trust a user to remember.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.