[java] string to string array conversion in java

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.

This question is related to java arrays string split

The answer is



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

Simply use the .toCharArray() method in Java:

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

This should work just fine in Java 8.


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.


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!


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]

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


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

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


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

/**
 * <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.


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.


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.


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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows