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.

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
riyana
  • 21,385
  • 10
  • 35
  • 34
  • 12
    I guess you do not mean `String[] ary = new String[] { "name" };`, what operation do you need? splitting in characters for instance? – rsp Aug 05 '10 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? – Woody Aug 05 '10 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 – riyana Aug 05 '10 at 10:04

15 Answers15

245

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.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
rsp
  • 23,135
  • 6
  • 55
  • 69
46
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.

f1sh
  • 11,489
  • 3
  • 25
  • 51
  • 26
    Does not really answer the question. – atamanroman Aug 05 '10 at 10:23
  • 3
    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. – f1sh Dec 18 '13 at 13:29
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.

Landei
  • 54,104
  • 13
  • 100
  • 195
  • 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 – riyana Aug 05 '10 at 10:05
  • @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 Jan 12 '13 at 22:42
  • @Behzad AFAIK you have the funny behavior with the empty entry only for empty patterns, not of you have some delimiter. – Landei Jan 13 '13 at 10:44
  • @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? – Behzad Jan 14 '13 at 08:02
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);
}
finnw
  • 47,861
  • 24
  • 143
  • 221
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;
}
GilZ
  • 6,418
  • 5
  • 30
  • 40
atamanroman
  • 11,607
  • 7
  • 57
  • 81
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]
fonji
  • 162
  • 1
  • 7
  • 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! ;) – varun Aug 31 '19 at 23:13
  • You save my life @fonji – Amit Sharma Feb 21 '20 at 10:26
7

Simply use the .toCharArray() method in Java:

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

This should work just fine in Java 8.

Jay Sullivan
  • 17,332
  • 11
  • 62
  • 86
Radhesh Khanna
  • 141
  • 3
  • 11
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);

thelost
  • 6,638
  • 4
  • 28
  • 44
  • 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 – riyana Aug 05 '10 at 10:05
3

Convert it to type Char?

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

Aidanc
  • 6,921
  • 1
  • 26
  • 30
  • 1
    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[]` =) – Axel Aug 05 '10 at 11:56
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!

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
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.

AGéoCoder
  • 812
  • 1
  • 10
  • 16
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().

ccpizza
  • 28,968
  • 18
  • 162
  • 169
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";
Pang
  • 9,564
  • 146
  • 81
  • 122
Rahul Chaube
  • 334
  • 3
  • 11
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.

Frank Hou
  • 1,688
  • 1
  • 16
  • 11
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

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393