I have a string like
"asdf a b c2 "
And I want to split it into an array like this:
["asdf", " ", "a", " ", " ", "b", " ", "c2", " "]
Using string.split(" ")
removes the spaces, resulting in this:
["asdf", "a", "", "b", "c2"]
I thought of inserting extra delimiters, e.g.
string.replace(/ /g, "| |").replace(/||/g, "|").split("|");
But this gives an unexpected result.
Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
To split a string without removing the delimiter: Use the str. split() method to split the string into a list. Use a list comprehension to iterate over the list. On each iteration, add the delimiter to the item.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.
Instead of splitting, it might be easier to think of this as extracting strings comprising either the delimiter or consecutive characters that are not the delimiter:
'asdf a b c2 '.match(/\S+|\s/g) // result: ["asdf", " ", "a", " ", " ", "b", " ", "c2", " "] 'asdf a b. . c2% * '.match(/\S+|\s/g) // result: ["asdf", " ", "a", " ", " ", "b.", " ", ".", " ", "c2%", " ", "*", " "]
A more Shakespearean definition of the matches would be:
'asdf a b c2 '.match(/ |[^ ]+/g)
To or (not to
)+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With