views:

601

answers:

5

I have a small problem here.I need to convert a string read from console into each character of string. For example string: "aabbab" I want to this string into array of string.How would I do that?

+4  A: 

If by array of String you mean array of char:

public class Test
{
    public static void main(String[] args)
    {
        String test = "aabbab ";
        char[] t = test.toCharArray();

        for(char c : t)
            System.out.println(c);    

        System.out.println("The end!");    
    }
}

If not, the String.split() function could transform a String into an array of String

See those String.split examples

/* String to split. */
String str = "one-two-three";
String[] temp;

/* delimiter */
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
  System.out.println(temp[i]);

The input.split("(?!^)") proposed by Joachim in his answer is based on:

  • a '?!' zero-width negative lookahead (see Lookaround)
  • the caret '^' as an Anchor to match the start of the string the regex pattern is applied to

Any character which is not the first will be split. An empty string will not be split but return an empty array.

VonC
thats an array of chars, not an array of strings
Chii
@Chii: true, I have illustrated both results now. `char[]` and `String[]`
VonC
very good illustration.
Zaki
A: 

You can use String.split(String regex):

String input = "aabbab";
String[] parts = input.split("(?!^)");
Since each character is a separator no character will be data, so you'll get an empty array.
Joachim Sauer
You are correct. Your regex is better.
Thanks don't know that it can be used with split but why it's splited with ?!^ ? cos a string doesn't have that in there?
gingergeek
@unknown: it's a regular expression that means "an empty string not preceded by the beginning of the string". So it matches on each space between characters and splits on that.
Joachim Sauer
+6  A: 
String[] result = input.split("(?!^)");

What this does is split the input String on all empty Strings that are not preceded by the beginning of the String.

Joachim Sauer
Thanks guys it works like magic.Cool
gingergeek
Good regex, +1.
VonC
+1  A: 

You mean you want to do "aabbab".toCharArray(); ? Which will return an array of chars. Or do you actually want the resulting array to contain single character string objects?

DaveJohnston
A: 

Use toCharArray() method. It splits the string into an array of characters:

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#toCharArray%28%29

String str = "aabbab";
char[] chs = str.toCharArray();
JuanZe