Reputation: 926
I have a String which looks like this "-..."
I would like to split it into 4 simple Strings "-"
"."
"."
"."
How can I achieve this?
String.split(".")
and String.toCharArray()
did not work.
Upvotes: 0
Views: 114
Reputation: 14885
"-...".split("(?!^)");
This will simply give the array of string for all the characters. For example the above will give the array of:
String[] (length=4) ["-", ".", ".", "."]
Upvotes: 2
Reputation: 82461
Split using the empty string as seperator:
"-...".split("")
Unfortunately this adds a empty string as the first element in java 7. (In java 8 it works fine).
Faraj Farook's solution works in java 7 and java 8.
Upvotes: 3
Reputation: 788
Use "-...".ToCharArray()
as it's working perfectly on my computer.
You might need to use "-...".ToCharArray()
instead of "-...".toCharArray()
.
Upvotes: 0
Reputation: 8378
you can convert charArray to string :
String string="-...";
char[] chars = string.toCharArray();
List<String> stringList = new ArrayList<>();
for (char stringChar : chars) {
stringList.add(String.valueOf(stringChar));
}
Upvotes: 0
Reputation: 10594
You can use some nice Java 8 functionality:
String[] foo = "-....".chars().mapToObj(String::new).toArray(String[]::new);
Upvotes: 2