2

If I have a String,

String x = "10 20 30 40";

Is there any way to convert it into an int array like this?

int[] y = {10, 20, 30, 40};
1
  • Is there any built-in method in java that can do this? Commented May 22, 2015 at 19:11

4 Answers 4

8

In a functional way, using Java 8 streams:

int[] y = Arrays.stream(x.split(" ")).mapToInt(Integer::parseInt).toArray();
Sign up to request clarification or add additional context in comments.

Comments

3
int[] convert(String x){
     String[] val = x.split(" ");
     int[] arr = new int[val.length];
     for (int i = 0; i < val.length; ++i){
          arr[i] = Integer.parseInt(val[i]);
     }
     return arr;
}

3 Comments

It should not be int[] arr = new int[val.size];, it should be int[] arr = new int[val.length]; I hope this is a type.
Sorry about the typo. The loop had val.length
This answer could be improved if you made more of an effort to explain what was going on in this code so that the asker has more of a hope of understanding it. I'm not a very big fan of "gimmeh teh codez" questions being rewarded with "gimmeh teh codez" answers.
-2

Maybe something like this, to get you started with your assignment :)? Using Strings split method with regular expressions.

String x = "10 20 30 40";
String[] cut = x.split(" ");

Now you have an array in cut. Then you'll need to loop through that and get the Integer value of the Strings, and do whatever more you need to..

happy coding!

1 Comment

why was this downvoted its not wrong, you should make your research instead of posting you assignments here
-4

You can combine the functions like the c++

find(character,range)

and

substring(initial position,range)

and a counter to increment the initial position

to create a vector with the elements as srting

and finally parse all the elements to the int type

(i didn know how to do that in java)

1 Comment

The question is about Java - if you don't know how to do it in Java, you'd better not answer the question. How to do it in C++ is not useful for the person who asked the question.

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.