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:29

Simply Use the .tocharArray() method in java

String k = "abc";
char alpha = k.tocharArray();

This should work just fine in JAVA 8

查看更多
与风俱净
3楼-- · 2019-01-02 15:30

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);
}
查看更多
刘海飞了
4楼-- · 2019-01-02 15:33

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

查看更多
深知你不懂我心
5楼-- · 2019-01-02 15:34

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]
查看更多
皆成旧梦
6楼-- · 2019-01-02 15:35
/**
 * <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.

查看更多
明月照影归
7楼-- · 2019-01-02 15:44

To start you off on your assignment, String.split splits strings on a regular expression, 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.

查看更多
登录 后发表回答