Related
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()});
This might have been asked before, but I spent some time looking, so here's what I have.
I have a string containing an array:
'["thing1","thing2"]'
I would like to convert it into an actual array:
["thing1","thing2"]
How would I do this?
You could create a loop that runs through the whole string, checking for indexes of quotes, then deleting them, along with the word. I'll provide an example:
ArrayList<String> list = new ArrayList<String>();
while(theString.indexOf("\"") != -1){
theString = theString.substring(theString.indexOf("\"")+1, theString.length());
list.add(theString.substring(0, theString.indexOf("\"")));
theString = theString.substring(theString.indexOf("\"")+1, theString.length());
}
I would be worried about an out of bounds error from looking past the last quote in the String, but since you're using a String version of an array, there should always be that "]" at the end. But this creates only an ArrayList. If you want to convert the ArrayList to a normal array, you could do this afterwards:
String[] array = new String[list.size()];
for(int c = 0; c < list.size(); c++){
array[c] = list.get(c);
}
You can do it using replace and split methods of String class, e.g.:
String s = "[\"thing1\",\"thing2\"]";
String[] split = s.replace("[", "").replace("]", "").split(",");
System.out.println(Arrays.toString(split));
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);
How to add a comma separated string to an ArrayList? My string "returnedItems" could hold 1 or 20 items which I'd like to add to my ArrayList "selItemArrayList".
After the ArrayList has been populated, I'd like to later iterate through it and format the items into a comma separated string with no spaces between the items.
String returnedItems = "a,b,c";
List<String> sellItems = Arrays.asList(returnedItems.split(","));
Now iterate over the list and append each item to a StringBuilder:
StringBuilder sb = new StringBuilder();
for(String item: sellItems){
if(sb.length() > 0){
sb.append(',');
}
sb.append(item);
}
String result = sb.toString();
One-liners are always popular:
Collections.addAll(arrayList, input.split(","));
split and asList do the trick:
String [] strings = returnedItems.split(",");
List<String> list = Arrays.asList(strings);
Simple one-liner:
selItemArrayList.addAll(Arrays.asList(returnedItems.split("\\s*,\\s*")));
Of course it will be more complex if you have entries with commas in them.
This can help:
for (String s : returnedItems.split(",")) {
selItemArrayList.add(s.trim());
}
//Shorter and sweeter
String [] strings = returnedItems.split(",");
selItemArrayList = Arrays.asList(strings);
//The reverse....
StringBuilder sb = new StringBuilder();
Iterator<String> iter = selItemArrayList.iterator();
while (iter.hasNext()) {
if (sb.length() > 0)
sb.append(",");
sb.append(iter.next());
}
returnedItems = sb.toString();
If the strings themselves can have commas in them, things get more complicated. Rather than rolling your own, consider using one of the many open-source CSV parsers. While they are designed to read in files, at least OpenCSV will also parse an individual string you hand it.
Commons CSV
OpenCSV
Super CSV
OsterMiller CSV
If the individual items aren't quoted then:
QString str = "a,,b,c";
QStringList list1 = str.split(",");
// list1: [ "a", "", "b", "c" ]
If the items are quoted I'd add "[]" characters and use a JSON parser.
You could use the split() method on String to convert the String to an array that you could loop through.
Although you might be able to skip the looping and parsing with a regular expression to remove the spaces using replaceAll() on a String.
String list = "one, two, three, four";
String[] items = list.split("\\p{Punct}");
List<String> aList = Arrays.asList(items);
System.out.println("aList = " + aList);
StringBuilder formatted = new StringBuilder();
for (int i = 0; i < items.length; i++)
{
formatted.append(items[i].trim());
if (i < items.length - 1) formatted.append(',');
}
System.out.println("formatted = " + formatted.toString());
import com.google.common.base.*;
Iterable<String> items = Splitter.on(",").omitEmptyStrings()
.split("Mango,Apple,Guava");
// Join again!
String itemsString = Joiner.join(",").join(items);
String csv = "Apple, Google, Samsung";
step one : converting comma separate String to array of String
String[] elements = csv.split(",");
step two : convert String array to list of String
List<String> fixedLenghtList = Arrays.asList(elements);
step three : copy fixed list to an ArrayList
ArrayList listOfString = new ArrayList(fixedLenghtList);
System.out.println("list from comma separated String : " + listOfString);
System.out.println("size of ArrayList : " + listOfString.size());
Output :
list of comma separated String : [Apple, Google, Samsung]
size of ArrayList : 3
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