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.
Answer from rsp on Stack Overflowstring to string array conversion in java - Stack Overflow
java - Converting String Array to an Integer Array - Stack Overflow
How to turn string into array
java - Convert String array to string back to string array - Stack Overflow
What is a string in Java?
Can we convert a string into a list instead of an array?
How to handle empty strings when converting to an array?
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.
You could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
Line by line
int [] v = Stream.of(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
With the Arrays.stream() alternative as
int [] v = Arrays.stream(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
However much better for parsing bigger chunks of text is
int [] v = Pattern.compile(",\\s+").splitAsStream(line)
.mapToInt(Integer::parseInt)
.toArray();
As this does not require the string array to be in memory, and we do an incremental parse to produce the integers. Moreover, as the input to splitAsStream is a CharSequece, and not just String, we can now also used buffered character sources to avoid even having the full input source in memory.
See also How do I create a Stream of regex matches? for some more interesting reading on incremental parsing.
Hello. I need help on turning a string example
String str = "Processor Mouse Power Supply Phone";
into an array of something like
String[][] arr = new String[]
arr[] = new String []{"Processor" , " Mouse" , "Power Supply" , "Phone"}
Also notice the "power supply " has two separate words. Any help is appreciated. Thank you
If the individual strings might themselves include a comma followed by a space, then this would not be feasible. Multiple String[] arrays could map to the same flat String, and an inverse function would not exist.
However, you note in a comment that your strings cannot include the comma separator. You can split the flat string back into the original substrings, using ", " (comma,space) as a separator.
APIs that support this include the standard Java String.split() method, and Guava's Splitter class.
Here's an example with Java's split() method:
public static void main(String[] args) {
String[] strs = new String[] { "Foo", "Bar", "Baz" };
String joined = Arrays.toString( strs );
String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);
// String.split()
String[] resplit = joinedMinusBrackets.split( ", ");
for ( String s : resplit ) {
System.out.println( s );
}
}
And here's an example with Guava's Splitter class:
public static void main(String[] args) {
String[] strs = new String[] { "Foo", "Bar", "Baz" };
String joined = Arrays.toString( strs );
String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);
// Guava Splitter class
List<String> resplitList = Splitter.on( ", " ).splitToList( joinedMinusBrackets );
for ( String s : resplitList ) {
System.out.println( s );
}
}
I guess that's the answer you're searching for. Briefly, it's about using serialization with apache codecs for encoding/decoding objects. I don't want to do copy/paste from another answer, so I'll give you only the code sample in case link changes someday. Here it is:
// serialize
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(yourArray);
//encode
String encodeString = new String(Hex.encodeHex(out.toByteArray()));
// deserialize
ByteArrayInputStream in = new ByteArrayInputStream(Hex.decodeHex(yourString.toCharArray()));
String yourArray = Arrays.toString((String[]) new ObjectInputStream(in).readObject());
}
// And then you could use `String#split()` method to convert string to array.
Another option is to use something like Gson JSON library, with Gson, you can convert any java object to a json string and then convert it back. Example code may looks like this:
//Put an array (or any other object to gson object
Gson gson = new Gson();
String json = gson.toJson(yourArray);
// Retrieve your object from gson
Gson gson = new Gson();
Array array = gson.fromJson(json, Array.class);
For more details you look this article.