String to String Array Conversion in Java

string to string array conversion in java

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.

How to convert String into String Array in Java?

Split on ",".

String st = "Tokyo, New York, Amsterdam"
String[] arr = st.split(",");

If st has '{' and '}'. You might want to do something along the lines of...

st = st.replace("{","").replace("}","");

to get rid of the '{' and '}'.

Convert ArrayListString to String[] array

Use like this.

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
System.out.println(s);

How to convert java array type string to string array?

How about deserializing the String with JSONArray:

import org.json.JSONArray;

String[] msgArray = {"aaa", "bbb", "ccc"};

// serializing
String msg = Arrays.toString(msgArray);

// deserializing
JSONArray jsonArray = new JSONArray(msg);
System.out.println(jsonArray.toList());

convert string [string] to string array

This text can be treated as JSON so you could try using JSON parser of your choice. For gson your code could look like.

String text = "[\"str1\",\"str2\"]"; // represents ["str1","str2"]

Gson gson = new Gson();

String[] array = gson.fromJson(text, String[].class);

System.out.println(array[0]); //str1
System.out.println(array[1]); //str2

If you are able to change the way server is sending you informations you can consider sending array object, instead of text representing array content. More info at

  • https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html
  • http://www.tutorialspoint.com/java/java_serialization.htm

or many other Java tutorials under serialization/deserialization.

Converting 'ArrayListString to 'String[]' in Java

List<String> list = ..;
String[] array = list.toArray(new String[0]);

For example:

List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);

The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

Convert array of strings into a string in Java

Java 8+

Use String.join():

String str = String.join(",", arr);

Note that arr can also be any Iterable (such as a list), not just an array.

If you have a Stream, you can use the joining collector:

Stream.of("a", "b", "c")
.collect(Collectors.joining(","))

Legacy (Java 7 and earlier)

StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();

Alternatively, if you just want a "debug-style" dump of an array:

String str = Arrays.toString(arr);

Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.

Android

Use TextUtils.join():

String str = TextUtils.join(",", arr);

General notes

You can modify all the above examples depending on what characters, if any, you want in between strings.

DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.

Correctly convert String array to String and back in java

You state that "Arrays.toString is absolutely not required."1

I suggest you serialize the Array to Base64:

public String serializeArray(final String[] data) {
try (final ByteArrayOutputStream boas = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(boas)) {
oos.writeObject(data);
return Base64.getEncoder().encodeToString(boas.toByteArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}

Then deserialize the Base64 to an array:

public String[] deserializeArray(final String data) {
try (final ByteArrayInputStream bias = new ByteArrayInputStream(Base64.getDecoder().decode(data));
final ObjectInputStream ois = new ObjectInputStream(bias)) {
return (String[]) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}

This requires Java 8.

Example:

public static void main(String args[]) throws Exception {
String[] stringArray = new String[]{"One,", "Two", "Three"};
String serialized = serializeArray(stringArray);
String[] deserialized = deserializeArray(serialized);
System.out.println(Arrays.toString(stringArray));
System.out.println(serialized);
System.out.println(Arrays.toString(deserialized));
}

Output

[One,, Two, Three]
rO0ABXVyABNbTGphdmEubGFuZy5TdHJpbmc7rdJW5+kde0cCAAB4cAAAAAN0AARPbmUsdAADVHdvdAAFVGhyZWU=
[One,, Two, Three]

Note, this works for any Object that implements Serializable, not just String[].


As a simple alternative, you could replace , by \, before joining the array and then also replace \, by , after splitting it. This relies on the standard "escaped delimiter" pattern that CSV uses. But it will fail if the user inputs \, somewhere in the input, so is less robust: YMMV.

public String serializeArray(final String[] data) {
return Arrays.stream(data)
.map(s -> s.replace(",", "\\,"))
.collect(joining(","));
}

public String[] deserializeArray(final String data) {
return Pattern.compile("(?<!\\\\),").splitAsStream(data)
.map(s -> s.replace("\\,", ","))
.toArray(String[]::new);
}

Convert String array to ArrayList

Use this code for that,

import java.util.Arrays;  
import java.util.List;
import java.util.ArrayList;

public class StringArrayTest {

public static void main(String[] args) {
String[] words = {"ace", "boom", "crew", "dog", "eon"};

List<String> wordList = Arrays.asList(words);

for (String e : wordList) {
System.out.println(e);
}
}
}

Java Convert String to Array [1,2,3,4,5,5] to [1,2,3,4,5,5]

I exactly, don't gather whether you want an array of Strings or an array of Integer as your result, but for the example, you have provided, this should work.

import java.util.Arrays;
class HelloWorld {
public static void main(String[] args) {
String x = "[\"a\",\"1\"]";
String[] array = x.split("\"");
array = Arrays.stream(array).filter(i -> i.matches("[\\dA-Za-z]")).toArray(String[]::new);
System.out.println(Arrays.toString(array));
}
}

I have filtered the array because initially there will be some empty strings and opening and closing braces as strings.



Related Topics



Leave a reply



Submit