string to string array conversion in java

2019-01-02 15:12发布

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.

标签: java string
15条回答
怪性笑人.
2楼-- · 2019-01-02 15:52

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().

查看更多
心情的温度
3楼-- · 2019-01-02 15:52

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";
查看更多
听够珍惜
4楼-- · 2019-01-02 15:54

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.

查看更多
登录 后发表回答