Reputation: 53
I want to split a string of form:
" 42 2152 12 3095 2"
into a list of integers, but when I use the .split(" ")
function I end up with an empty ""
element at the beginning due to the whitespace at the start. Is there a way to split this without the empty element?
Upvotes: 0
Views: 151
Reputation: 1007
As per above answers and you are asking the performance difference between all these methods:
There is no real performance difference all of these would run with O(n).
Actually, splitting the strings first like , and then adding them to a collection will contain 2 x O(n) loops.
Upvotes: 1
Reputation: 787
You can use Scanner
, it will read one integer at a time from string
Scanner scanner = new Scanner(number);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
Upvotes: 1
Reputation: 469
Use the String.trim() function before you call split on the array. This will remove any white-spaces before and after your original string
For example:
String original = " 42 2152 12 3095 2";
original = original.trim();
String[] array = original.split(" ");
To make your code neater, you could also write it as:
String original = " 42 2152 12 3095 2";
String[] array = original.trim().split(" ");
If we print the array out:
for (String s : array) {
System.out.println(s);
}
The output is:
42
2152
12
3095
2
Hope this helps.
Upvotes: 2
Reputation: 23329
You can use String.trim
to remove leading and trailing whitespace from the original string
String withNoSpace = " 42 2152 12 3095 2".trim();
Upvotes: 2