Efficiently converting a space separated String of numbers into an integer array in Java

Hi. I’m quite new to CP. I use Java.

I often notice in contests that we are given a String of space separated integers as inputs, which we have to convert into an integer array to perform operations on them. What I do is split the String (String a[] = str.split(" "):wink: to convert it into a String array and then use for loop to convert it into an integer array.

What I mean to ask is whether there is a better way of doing so, i.e., converting it into an integer array using less number of code steps, i.e., whether there is any in-built java function which may help me.

Thanks :slight_smile:

1 Like

Hey @akashbhalotia, you can use Scanner’s nextInt which would eliminate the need of the String array, but you would still require the for loop. Also Scanner is painfully slow, so I wouldn’t recommend this. Apart from this I am quite certain there are no other library functions that can do what you’re looking for.
What I have seen many programmers do is that they make a template for themselves which contains convenient functions for getting parsed input. You can simply copy and paste such a template for each program you do. You’re welcome to use my template, but it is generally not a good idea to use a piece of code you don’t understand because you wouldn’t be able to adapt it to your needs. So I encourage you to either understand how it works and make changes for your own use as necessary, or make your own template from scratch.
Hope this helps, and good luck here :slight_smile:


I think Scanner works when submitting in contests. I cant actually answer your question much cause I use c, c++ (where I just take input as int etc.) but if I remember correctly, a user’s submission in Scanner was also accepted (But not many people recommend using scanner so yeah…)

Even I want to now hear from somebody regarding this haha!

EDIT- Lol, it took me 15 minutes to think and write this, and I didn’t refresh the page, so lol.
@meow has really explained things wonderfully!

No, there is no other way to take a int array as input in Java. What I suggest is if you use a good IDE( Eg. Eclipse) you should save these as templates.(like sysout CTRL+SPACE = System.out.println(), which is inbuilt in eclipse). This should save time.

However, there is no inbuilt support. You have to use str.split(" "); function. And so take input using a BufferedReader as Scanner is slow. You can also save the templates that most people use after understanding how it works.

1 Like

Hey, thanks , but I had seen something like str.toCharArray() on the web. Thought that there might be something similar for integers…