Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string with no delimiter

I want to split a string like "My dog" into an array of:

| M | y | space char will be in here | D | o | g |

Here is my code:

String []in_array;
    input = sc.next();  
in_array = input.split(""); //Note this there is no delimiter 

for(int k=1; k < in_array.length; k++){
    System.out.print(" "+in_array[k]);
}

EDIT:

It only prints out "My"

like image 622
MosesA Avatar asked Dec 01 '22 04:12

MosesA


2 Answers

java.lang.String has a toCharArray() that does exactly that.

like image 166
Aleksander Blomskøld Avatar answered Dec 04 '22 15:12

Aleksander Blomskøld


If all you see if "My", that is all you have in your input string. Did you use Scanner.next() ?

for(String s : "My dog".split(""))
    System.out.println(s);

prints

{empty line}
M
y

d
o
g
like image 30
Peter Lawrey Avatar answered Dec 04 '22 15:12

Peter Lawrey