142

I have a string = "name"; I want to convert into a string array. How do I do it? Is there any java built in function? Manually I can do it but I'm searching for a java built in function.

I want an array where each character of the string will be a string. like char 'n' will be now string "n" stored in an array.

3
  • 13
    I guess you do not mean String[] ary = new String[] { "name" };, what operation do you need? splitting in characters for instance? Commented Aug 5, 2010 at 10:00
  • Do you mean a string array? How could you have a function for that, it would just be: String[] array = {"Name"}; or do you mean a character array? Commented Aug 5, 2010 at 10:01
  • 1
    i want an array where each character of the string will be a string. like char 'n' will be now string "n" stored in an array Commented Aug 5, 2010 at 10:04

15 Answers 15

250

To start you off on your assignment, String.split splits strings on a regular expression and this expression may be an empty string:

String[] ary = "abc".split("");

Yields the array:

(java.lang.String[]) [, a, b, c]

Getting rid of the empty 1st entry is left as an exercise for the reader :-)

Note: In Java 8, the empty first element is no longer included.

Sign up to request clarification or add additional context in comments.

Comments

47
String strName = "name";
String[] strArray = new String[] {strName};
System.out.println(strArray[0]); //prints "name"

The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:

String[] strArray = new String[1];

instead, the length is determined by the number of elements in the initalizer. Using

String[] strArray = new String[] {strName, "name1", "name2"};

creates an array with a length of 3.

2 Comments

Does not really answer the question.
Check the question's revision history and you will see that the question is asking for something different before it was edited. This answer replies to the first version.
16

I guess there is simply no need for it, as it won't get more simple than

String[] array = {"name"};

Of course if you insist, you could write:

static String[] convert(String... array) {
   return array;
}

String[] array = convert("name","age","hobby"); 

[Edit] If you want single-letter Strings, you can use:

String[] s = "name".split("");

Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.

4 Comments

i want an array where each character of the string will be now itself a string. like char 'n' will be now string "n" stored in an array
@Landei I have this String date="2013/01/05" and when I use .split("/"), it doesn't return empty string as [0] and it works fine. Is there any difference between my regular expression splitter and yours?
@Behzad AFAIK you have the funny behavior with the empty entry only for empty patterns, not of you have some delimiter.
@Landei Let me know that I got your mean. You mean that only using the "" in split function return 0 as first array value? yes?
15

Assuming you really want an array of single-character strings (not a char[] or Character[])

1. Using a regex:

public static String[] singleChars(String s) {
    return s.split("(?!^)");
}

The zero width negative lookahead prevents the pattern matching at the start of the input, so you don't get a leading empty string.

2. Using Guava:

import java.util.List;

import org.apache.commons.lang.ArrayUtils;

import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;

// ...

public static String[] singleChars(String s) {
    return
        Lists.transform(Chars.asList(s.toCharArray()),
                        Functions.toStringFunction())
             .toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}

1 Comment

That regexp is the best IMO. Beware that Java 8 fixed that particular issue anyway.
12

In java 8, there is a method with which you can do this: toCharArray():

String k = "abcdef";
char[] x = k.toCharArray();

This results to the following array:

[a,b,c,d,e,f]

2 Comments

Although not a string array, this is perfect for cases where you need characters instead of silly accesses to String.charAt(0) on the single character strings unnecessarily! ;)
You save my life @fonji
12
String data = "abc";
String[] arr = explode(data);

public String[] explode(String s) {
    String[] arr = new String[s.length];
    for(int i = 0; i < s.length; i++)
    {
        arr[i] = String.valueOf(s.charAt(i));
    }
    return arr;
}

Comments

7

Simply use the .toCharArray() method in Java:

String k = "abc";
char[] alpha = k.toCharArray();

This should work just fine in Java 8.

Comments

5

String array = array of characters ?

Or do you have a string with multiple words each of which should be an array element ?

String[] array = yourString.split(wordSeparator);

1 Comment

i want an array where each character of the string will be a string. like char 'n' will be now string "n" stored in an array
3

Convert it to type Char?

http://www.javadb.com/convert-string-to-character-array

1 Comment

Why is this downvoted ? It kind of looks like a solution to what had been asked (for as much as I can understand it anyway)... Even though I think you meant char[] =)
2

You could use string.chars().mapToObj(e -> new String(new char[] {e}));, though this is quite lengthy and only works with java 8. Here are a few more methods:

string.split(""); (Has an extra whitespace character at the beginning of the array if used before Java 8) string.split("|"); string.split("(?!^)"); Arrays.toString(string.toCharArray()).substring(1, string.length() * 3 + 1).split(", ");

The last one is just unnecessarily long, it's just for fun!

Comments

2

An additional method:

As was already mentioned, you could convert the original String "name" to a char array quite easily:

String originalString = "name";
char[] charArray = originalString.toCharArray();

To continue this train of thought, you could then convert the char array to a String array:

String[] stringArray = new String[charArray.length];
for (int i = 0; i < charArray.length; i++){
    stringArray[i] = String.valueOf(charArray[i]);
}

At this point, your stringArray will be filled with the original values from your original string "name". For example, now calling

System.out.println(stringArray[0]);

Will return the value "n" (as a String) in this case.

Comments

2

here is have convert simple string to string array using split method.

String [] stringArray="My Name is ABC".split(" ");

Output

stringArray[0]="My";
stringArray[1]="Name";
stringArray[2]="is";
stringArray[3]="ABC";

Comments

2

Splitting an empty string with String.split() returns a single element array containing an empty string. In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with org.apache.commons.lang3.StringUtils.split(str).

import org.apache.commons.lang3.StringUtils;

StringUtils.split(null)       => null
StringUtils.split("")         => []
StringUtils.split("abc def")  => ["abc", "def"]
StringUtils.split("abc  def") => ["abc", "def"]
StringUtils.split(" abc ")    => ["abc"]

Another option is google guava Splitter.split() and Splitter.splitToList() which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on null:

import com.google.common.base.Splitter;

Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();

SPLITTER.split("a,b,   c , , ,, ")     =>  [a, b, c]
SPLITTER.split("")                     =>  []
SPLITTER.split("  ")                   =>  []
SPLITTER.split(null)                   =>  NullPointerException

If you want a list rather than an iterator then use Splitter.splitToList().

Comments

1
/**
 * <pre>
 * MyUtils.splitString2SingleAlphaArray(null, "") = null
 * MyUtils.splitString2SingleAlphaArray("momdad", "") = [m,o,m,d,a,d]
 * </pre>
 * @param str  the String to parse, may be null
 * @return an array of parsed Strings, {@code null} if null String input
 */
public static String[] splitString2SingleAlphaArray(String s){
    if (s == null )
        return null;
    char[] c = s.toCharArray();
    String[] sArray = new String[c.length];
    for (int i = 0; i < c.length; i++) {
        sArray[i] = String.valueOf(c[i]);
    }
    return sArray;
}

Method String.split will generate empty 1st, you have to remove it from the array. It's boring.

Comments

1

Based on the title of this question, I came here wanting to convert a String into an array of substrings divided by some delimiter. I will add that answer here for others who may have the same question.

This makes an array of words by splitting the string at every space:

String str = "string to string array conversion in java";
String delimiter = " ";
String strArray[] = str.split(delimiter);

This creates the following array:

// [string, to, string, array, conversion, in, java]

Source

Tested in Java 8

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.