Hans En
Hans En

Reputation: 926

How can I split a String of dots?

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

Answers (5)

Faraj Farook
Faraj Farook

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

fabian
fabian

Reputation: 82461

Split using the empty string as seperator:

"-...".split("")

Edit:

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

arpit
arpit

Reputation: 788

Use "-...".ToCharArray() as it's working perfectly on my computer. You might need to use "-...".ToCharArray() instead of "-...".toCharArray().

Upvotes: 0

Sachin Gupta
Sachin Gupta

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

Patrick Collins
Patrick Collins

Reputation: 10594

You can use some nice Java 8 functionality:

String[] foo = "-....".chars().mapToObj(String::new).toArray(String[]::new);

Upvotes: 2

Related Questions