user3339618
user3339618

Reputation: 25

How to break a string into many variables

Is it possible in Java to break a String into many individual int variables?

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

Like

int var1 = 1;

int var2 = 2;

int var3 = 3;

and so on.

Thanks

Upvotes: 0

Views: 106

Answers (3)

Don Chakkappan
Don Chakkappan

Reputation: 7560

split() method is more apt one.One of the other way is use StringTokenizer class, as follows

    String abc = "1,2,3,4";

    int i = 0;
    StringTokenizer st = new StringTokenizer(abc,","); 
    int array[] = new int[st.countTokens()];
    while (st.hasMoreTokens()) {
        array[i] = Integer.parseInt(st.nextToken().toString());
        i++;
    }

I know your problem is already solved.But this code snippet is just to introduce use of StringTokenizer

Upvotes: 0

Zied R.
Zied R.

Reputation: 4964

String s = "1,2,3,4,5,6";
String[] vars = s.split(",");
int [] varIn= new int[vars.lenght]

for (int i=0;i<vars.lenght;i++)
{
  varIn[i]= Integer.parseInt(vars[i]);
}

.

==> varIn[0]=1;
    varIn[1]=2;
    etc.. 

Upvotes: 4

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44449

You cannot dynamically allocate the values to each variable unless you use reflection.

What you can do is split the string on the commas, convert each token into an integer and put these values inside a collection.

For example:

int[] result;
String s = "1,2,3,4,5,6";
String[] tokens = s.split(",");
result = new int[tokens.length];

for(int i = 0; i < tokens.length; i++){
    result[i] = Integer.parseInt(tokens[i]);
}

Now you can access each value in the result array (perhaps by assigning var1 to result[1]).

As said: you can also add it to the variables directly using reflection but that's usually a sign that your design went wrong somewhere.

Upvotes: 0

Related Questions