string to string array conversion in java - 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.

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.

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.

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

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

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

Convert it to type Char?
http://www.javadb.com/convert-string-to-character-array

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!

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.

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

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

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

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

Related

Java - Split and trim in one shot

I have a String like this : String attributes = " foo boo, faa baa, fii bii," I want to get a result like this :
String[] result = {"foo boo", "faa baa", "fii bii"};
So my issue is how should to make split and trim in one shot i already split:
String[] result = attributes.split(",");
But the spaces still in the result :
String[] result = {" foo boo", " faa baa", " fii bii"};
^ ^ ^
I know that we can make a loop and make trim for every one but I want to makes it in shot.
Use regular expression \s*,\s* for splitting.
String result[] = attributes.split("\\s*,\\s*");
For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:
String result[] = attributes.trim().split("\\s*,\\s*");
Using java 8 you can do it like this in one line
String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);
If there is no text between the commas, the following expression will not create empty elements:
String result[] = attributes.trim().split("\\s*,+\\s*,*\\s*");
You can do it with Google Guava library this way :
List<String> results = Splitter.on(",").trimResults().splitToList(attributes);
which I find quite elegant as the code is very explicit in what it does when you read it.
ApaceCommons StringUtils.stripAll function can be used to trim individual elements of an array. It leaves the null as null if some of your array elements are null.
Here,
String[] array = StringUtils.stripAll(attributes.split(","));
create your own custom function
private static String[] split_and_trim_in_one_shot(String string){
String[] result = string.split(",");
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
Overload with a consideration for custom delimiter
private static String[] split_and_trim_in_one_shot(String string, String delimiter){
String[] result = string.split(delimiter);
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
with streams
public static List<String> split(String str){
return Stream.of(str.split(","))
.map(String::trim)
.map (elem -> new String(elem))//optional
.collect(Collectors.toList());
What about spliting with comma and space:
String result[] = attributes.split(",\\s");
// given input
String attributes = " foo boo, faa baa, fii bii,";
// desired output
String[] result = {"foo boo", "faa baa", "fii bii"};
This should work:
String[] s = attributes.trim().split("[,]");
As answered by #Raman Sahasi:
before you split your string, you can trim the trailing and leading spaces. I've used the delimiter , as it was your only delimiter in your string
String result[] = attributes.trim().split("\\s*,[,\\s]*");
previously posted here: https://blog.oio.de/2012/08/23/split-comma-separated-strings-in-java/
Best way is:
value.split(",").map(function(x) {return x.trim()});

Whats wrong with the following code

Why isn't the following code working ?
String s = "fecbda";
Arrays.sort(s.toCharArray());
System.out.println(s);
Strings are immutable so you can't change them, and you shouldn't expect this to do anything.
What you might have intended is
String s = "fecbda";
char[] chars = s.toCharArray();
Arrays.sort(chars);
String s2 = new String(chars);
System.out.println(s2);
It does not work as s.toCharArray():
Returns:
a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
The operative part of the documentation is that it creates a new array (i.e. a copy of the characters in the string) and when you sort that array you do not sort the String.
You cannot sort the string as it is immutable but you can make a new string out of the sorted character array like this:
String s = "fecbda";
char[] c = s.toCharArray();
Array.sort( c );
String n = new String( c );
As an alternative method, you can do it in Java 8 using streams:
String s = "fecbda";
String n = s.chars() // Convert to an IntStream of character codes
.sorted() // Sort
.mapToObj(i -> Character.toString((char) i)) // Convert to strings
.collect(Collectors.joining()); // Concatenate the strings.

How to put Java String to array

I have a java String of a list of numbers with comma separated and i want to put this into an array only the numbers. How can i achieve this?
String result=",17,18,19,";
First remove leading commas:
result = result.replaceFirst("^,", "");
If you don't do the above step, then you will end up with leading empty elements of your array. Lastly split the String by commas (note, this will not result in any trailing empty elements):
String[] arr = result.split(",");
One liner:
String[] arr = result.replaceFirst("^,", "").split(",");
String[] myArray = result.split(",");
This returns an array separated by your argument value, which can be a regular expression.
Try split()
Assuming this as a fixed format,
String result=",17,18,19,";
String[] resultarray= result.substring(1,result.length()).split(",");
for (String string : resultarray) {
System.out.println(string);
}
//output : 17 18 19
That split() method returns
the array of strings computed by splitting this string around matches of the given regular expression
You can do like this :
String result ="1,2,3,4";
String[] nums = result.spilt(","); // num[0]=1 , num[1] = 2 and so on..
String result=",17,18,19,";
String[] resultArray = result.split(",");
System.out.printf("Elements in the array are: ");
for(String resultArr:resultArray)
{
System.out.println(resultArr);
}

Splitting string at specified point [duplicate]

This question already has answers here:
How to separate specific elements in string java
(3 answers)
Closed 9 years ago.
so the method takes two parameters, first is the String you will be splitting, second is the delimiter(where to split at).
So if I pass in "abc|def" as the first parameter and "|" as the second I should get a List that returns "abc, def" the problem I'm having is that my if statement requires the delimiter is in the current string to be accessed. I can't think of a better condition, any help?
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
for(int i=0;i<string.length();i++){
newString += string.charAt(i);
if(newString.contains(delimiter)){
//list.remove(string);
list.add(newString.replace(delimiter, ""));
newString="";
}
}
return list;
}
Badshaah and cmvaxter code for split using builtin function split(regex) won't work. as you pass "|" as a delimiter "sam|ple" it wont be splitted as [sam,ple] because ( | , + , * , ...) are all used in regex for other purposes.
and u can check character by character, if the delimiter is a character
loop(each char)
if(not delim)
append to list[i]
else
increment i, discard char
learning purpose it might be needed in c or c++ (even they 've strtok to split strings) to improve effeciency or to modify something differently. [may split differently not using regex]
Its best to use existing system libraries and functions.
if u want to use your function do something like
write these functions yourself
findpos(delim) // gives position of delimiter found in string
substring(pos,len) //len:size of delimiter
getlist(String str,String delim)
//for each delim found use substring and append to list
use some pattern matching algorithms like KMP or something u know.
Change your whole method to.
public List<String> splitIt(String string, String delimiter){
String[] out = string.split(delimiter);
return Arrays.asList(out);
}
Since you are iterating through the string, your if should be based on the character you are inspecting, instead of invoking contains each time:
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
int lastDelimiter = 0;
for (int i=0; i<string.length(); i++) {
if (delimiter.equals("" + string.charAt(i))) {
list.add(string.substring(lastDelimiter, i));
lastDelimiter = i + 1;
}
}
if (lastDelimiter != string.length())
list.add(string.substring(lastDelimiter, string.length()));
return list;
}
For the sake of learning, I think your original attempt lends itself to a recursive solution. The general idea in this case would be:
If there are no delimiters in the string and it is not empty, return the string as the only element in a new list
Otherwise
find the first occurrence of the delimiter
extract the string from the beginning up to the delimiter, call it 'found'
remove the delimiter
recursively call this method, passing it the remainder of the string and the delimiter
append 'found' to the list returned from #4, and return that list
The String class already supports a split method that I believe does exactly what you are looking to do.
String[] s = "abc|def".split("\\|");
List<String> list = Arrays.asList(s);
If you want to do it yourself, the code might look something like this:
char delim = "|".charAt(0);
String s = "abc|def|ghi";
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder();
List<String> list = new ArrayList<String>();
for(char c: chars){
if (c == delim){
list.add(sb.toString());
sb = new StringBuilder();
}
else{
sb.append(c);
}
}
if (sb.length() > 0) list.add(sb.toString());
System.out.println(list);

Java Convert String[] to Byte[] making sure to skip empty strings

I need to convert String[] to Byte[] in Java. Essentially, I have a space delimited string returned from my database. I have successfully split this String into an array of string elements, and now I need to convert each element into a byte, and produce a byte[] at the end.
So far, the code below is what I have been able to put together but I need some help making this work please, as the getBytes() function returns a byte[] instead of a single byte. I only need a single byte for the string (example string is 0xd1 )
byte[] localbyte = null;
if(nbytes != null)
{
String[] arr = (nbytes.split(" "));
localbyte = new byte[arr.length];
for (int i=0; i<localbyte.length; i++) {
localbyte[i] = arr[i].getBytes();
}
}
I assume you'd like to split strings like this:
"Hello world!"
Into "Hello", "world!" instead of "Hello", " ", "world!"
If that's the case, you can simply tweak on the split regex, using this instead:
String[] arr = (nbytes.split(" +"));
You should be familiar with regular expression. Instead of removing empty string after splitting, you can split the string with one or more white space:
To split a string by space or tab, you can use:
String[] arr = (nbytes.split("\\p{Blank}+"));
E.g.
"Hello \tworld!"
results in
"Hello","world!"
To split a string by any whitespace, you can use:
String[] arr = (nbytes.split("\\p{Space}+"));
E.g
"Hello \tworld!\nRegular expression"
results in
"Hello","world!","Regular","expression"
What about Byte(String string) (Java documentation).
Also you might want to look up Byte.parseByte(string) (doc)
byte[] localbyte = null;
if(nbytes != null)
{
String[] arr = (nbytes.split(" "));
localbyte = new byte[arr.length];
for (int i=0; i<localbyte.length; i++) {
localbyte[i] = new Byte(arr[i]);
}
}
Notice:
The characters in the string must all be decimal digits, except that
the first character may be an ASCII minus sign '-' ('\u002D') to
indicate a negative value.
So you might want to catch the NumberFormatException.
If this is not what your looking for maybe you can provide additional information about nbytes ?
Also Michael's answer could turn out helpful: https://stackoverflow.com/a/2758746/1063730

Categories

Resources