Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to string array conversion in java

People also ask

How do I convert a string array to an array in Java?

String class split(String regex) can be used to convert String to array in java. If you are working with java regular expression, you can also use Pattern class split(String regex) method.

Can we convert a string to character array in Java?

The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.


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.


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.


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);
}

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.