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?
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.
You can use String.trim to remove leading and trailing whitespace from the original string
String withNoSpace = " 42 2152 12 3095 2".trim();
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());
}
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.
Related
I'm reading from a .csv File line by line. One line could look for example as following: String str = "10,1,,,,".
Now I would like to split according to ",": String[] splitted = str.split(","); The problem now is that this only results in 2 elements but I would like to have 5 elements, the first two elements should contain 10 and 1 and the other 3 should be just an empty String.
Another example is String str = "0,,,,," which results in only one element but I would like to have 5 elements.
The last example is String str = "9,,,1,," which gives 2 elements (9 and 1), but I would like to have 5 elements. The first element should be 9 and the fourth element should be 1 and all other should be an empty String.
How can this be done?
You need to use it with -1 parameter
String[] splitted = str.split(",", -1);
This has been discussed before, e.g.
Java: String split(): I want it to include the empty strings at the end
But split really shouldn't be the way you parse a csv, you could run into problems when you have a String value containing a comma
23,"test,test","123.88"
split would split the row into 4 parts:
[23, "test, test", "123.88"]
and I don't think you want that.
split only drops trailing delimeters by default. You can turn this off with
String str = "9,,,1,,";
String[] parts = str.split(",", -1);
System.out.println(Arrays.toString(parts));
prints
[9, , , 1, , ]
Pass -1 (or any negative number, actually) as a second parameter to split:
System.out.println("0,,,,,".split(",", -1).length); // Prints 6.
I thought a problem for a day but still cannot solve it.
I have a formula input like "11+1+1+2". without space
I want to split the formula according to the operator.
Then I wrote like these:
String s = "11+1+1+2";
String splitByOp[] = s.split("[+|-|*|/|%]");
for(int c=0; c < splitByOp.length; c++){
System.out.println(splitByOp[c]);
The output is:
11
1
1
2
I want to put the operand(the output) and also the operator(+) into an ArrayList. But how can I keep the operator after spliting them?
I try to have one more Array to split the number.
String operator[] = s.split("\\d");
But the result is 11 become 1 1. The length of operator[] is 5.
In other words, how can I perform like:
The output:
11
+
1
+
1
+
2
You need to split on a regex that is non consuming. Specifically, on "word boundary":
String[] terms = s.split("\\b");
A "word boundary" is the gap between the word char and a non-word char, but digits are classified as word chars. Importantly, the match is non-consuming, so all of the content of the input is preserved in the split terms.
Here's some test code:
String s = "11+1+1+2";
String[] terms = s.split("\\b");
for (String term : terms)
System.out.println(term);
Output:
11
+
1
+
1
+
2
public static void main(String[] args) {
String s = "11+1+1+2";
String[] terms = s.split("(?=[+])|(?<=[+])");
System.out.println(Arrays.toString(terms));
}
output
[11, +, 1, +, 1, +, 2]
You could combine lookahead/lookbehind assertions
String[] array = s.split("(?=[+])|(?<=[+])");
I have a String and I want to split it by ","
If suppose I have a String like,
String test = "aa,bb,cc";
now I can split it by,
String[] spl = test.split(",");
And the spl.length is 3
If suppose my String is
String test = ",,,";
Here the splitted String length is 0. But my expected answer is 3.
My test String is dynamaic value and it may varies like, Now think I have a String like
String test = ",aa,dd,,,,,ff,gg"
Now the splited array length is 4. But I expected answer is 9
And I need to split by "," and I need the aa position at spl[1] and dd position as spl[2] and ff position as spl[7]
Can someone give the suggestion about to solve this issue..
Use split() with -1 as limit
public static void main(String[] args) {
String test = ",,,";
System.out.println(Arrays.toString(test.split(",", -1))); // adds leading and trailing empty Strings .
// so effectively its like adding "" before , after and between each ","
String test1 = "aa,bb,cc";
System.out.println(Arrays.toString(test1.split(",",-1)));
}
O/P :
[, , , ] -- > Length =4
[aa, bb, cc]
To get the behavior you want you can just replace "," by " ,":
String test = ",,";
test = test.replace(",", " ,");
System.out.println((test.split(",").length));
With the split() function, java separates a String by the Substring of your choice. If there is nothing between them, the field will not be null, it will just be skipped.
In other programming languages, you could come across something like this:
String example = ',,,'
String[] example2 = example.split(',')
print(example2.length())
This could also deliver 4. Because there are 4 spaces around the ',' chars:
1,2,3,4
Suppose I have String s = "123 USA" , how can I obtain only the number i.e '123' that is in the String? By that I mean what is the most efficient way of doing it?
Split the String on the space character.
For each String in the resulting String[], use the method from this answer to determine whether it is a valid integer or not. If it is a valid integer, then output that integer. Otherwise, ignore it.
If you know where the numbers are in the the string, i would do something like this.
String[] split = s.split();
This will give you an array equivalent to
String[] split = ["123", "USA"];
The split function will default to splitting by spaces(I believe).
From there you can use
int num = Integer.parseInt(split[0]);
// num = 123;
to convert the fist index of the split array into an int.
s.replaceAll("\\D+", " ").trim()
\\D+ matches non-digits
trim() clears whitespace
Example:
String testString = " ##!#! (!#)!# 123 USA 312";
Output: 123 312
If there is more than one number, the next step may be to use String.split().
To convert a String to an integer: Integer.parseInt(string)
I have a java String of a list of numbers with comma separated and i want to put this into an array only the numbers. How can i achieve this?
String result=",17,18,19,";
First remove leading commas:
result = result.replaceFirst("^,", "");
If you don't do the above step, then you will end up with leading empty elements of your array. Lastly split the String by commas (note, this will not result in any trailing empty elements):
String[] arr = result.split(",");
One liner:
String[] arr = result.replaceFirst("^,", "").split(",");
String[] myArray = result.split(",");
This returns an array separated by your argument value, which can be a regular expression.
Try split()
Assuming this as a fixed format,
String result=",17,18,19,";
String[] resultarray= result.substring(1,result.length()).split(",");
for (String string : resultarray) {
System.out.println(string);
}
//output : 17 18 19
That split() method returns
the array of strings computed by splitting this string around matches of the given regular expression
You can do like this :
String result ="1,2,3,4";
String[] nums = result.spilt(","); // num[0]=1 , num[1] = 2 and so on..
String result=",17,18,19,";
String[] resultArray = result.split(",");
System.out.printf("Elements in the array are: ");
for(String resultArr:resultArray)
{
System.out.println(resultArr);
}