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()});
Related
I have an input stream which has fields separated by tab(\t)
which looks like this
String str = " acc123\tdpId123\t2011-01-01\t2022-01-01\thello#xyz.com\tIN\t1233\tSOMETHING ";
which works fine when I do str = str.trim(); and
strArray = str.split("\t", -1);
strArray=["acc123","dpId123","2011-01-01","2022-01-01","hello#xyz.com","IN","1233","SOMETHING"] will give size as 8
But last field in the input record is not mandatory and can be skipped.
So the input can look like this too.
String str1 = "acc123\tdpId123\t2011-01-01\t2022-01-01\thello#xyz.com\tIN\t1233\t";
but in this case last field should be empty but when I use this string after trim and split my size is 7
str1 = str1.trim();
strArray = str1.split("\t", -1);
strArray=["acc123","dpId123","2011-01-01","2022-01-01","hello#xyz.com","IN","1233"]will give size as 7
But I want
strArray=["acc123","dpId123","2011-01-01","2022-01-01","hello#xyz.com","IN","1233",""]
How can I avoid this situation?
There you go:
String str1 = " acc123\tdpId 123\t201 1-01-01\t2022-01-01\thello#xyz.com\tIN\t1233\t";
str1 = str1.replaceAll("^[ ]+", ""); // removing leading spaces
str1 = str1.replaceAll("[ ]+$", ""); // removing trailing spaces
String[] split = str1.split("\t", -1);
System.out.println(Arrays.toString(split));
System.out.println(split.length);
String#trim method also removes \t. To handle that I have removed only the leading and trailing spaces using regex.
Output:
[acc123, dpId 123, 201 1-01-01, 2022-01-01, hello#xyz.com, IN, 1233, ]
8
You can use split like so :
String[] split = str.split("\t", -1); // note the -1
To avoid spaces you can use
Arrays.stream(split).map(String::trim).toArray(String[]:new);
you can use limit parameter to solve this str.split("\t",-1) .
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
read more about split limit in the docs.
Example:
public class GFG {
public static void main(String args[])
{
String str = "a\tb\tc\t";
String[] arrOfStr = str.split("\t",-1);
for (String a : arrOfStr)
System.out.println(a);
System.out.println(arrOfStr.length);
}
}
The conceptually correct way to do this in your case is to split first, only then trim first and last elements:
String[] array = str.split("\t");
array[0] = array[0].trim();
int last = array.length -1;
if (last > 0) {
array[last] = array[last].trim();
}
Also, if you know upfront how many fields there is supposed to be, then you should also use that knowledge, otherwise you can get an invalid number of fields still:
int fieldsCount = getExpectedFieldsCount();
String[] array = str.split("\t", fieldsCount);
Lastly, I advise you to not use whitespace as the data separator. Use something else. For example, see CSV format, it's a lot better for these things.
Try this (the result array is in the variable resultArray):
String str1 = "acc123\tdpId123\t2011-01-01\t2022-01-01\thello#xyz.com\tIN\t1233\t";
String[] strArray = str1.split("\t");
String regex = ".*\\t$";
String[] resultArray;
if (str1.matches(regex)) {
resultArray = new String[strArray.length + 1];
resultArray[strArray.length] = "";
} else {
resultArray = new String[strArray.length];
}
for (int i= 0; i < strArray.length; i++) {
resultArray[i] = strArray[i];
}
System.out.println(resultArray.length);
System.out.println(Arrays.toString(resultArray));
I have a String as param1=HUvguys83789r8==== i have to split this with = delimiter. I have tried with String.split("=") as well as i have used StringUtils too but i cannot split it correctly. Can some one help me out for this.
String parameters = "param1=HUvguys83789r8===="
String[] string = StringUtils.split(parameters, "=");
parameters.split("=");
And i got my output as [param1, HUvguys83789r8]
I need the output as [param1, HUvguys83789r8====]
You really only want to split on the first occurrence of =, so do that
parameters.split("=", 2)
The overloaded split(String, int) javadoc states
If the limit n is greater than zero then the pattern will be applied
at most n - 1 times, the array's length will be no greater than n, and
the array's last entry will contain all input beyond the last matched
delimiter.
I would use String#indexOf(char ch) like so,
private static String[] splitParam(String in) {
int p = in.indexOf('=');
if (p > -1) {
String key = in.substring(0, p);
String value = in.substring(p + 1);
return new String[] {key, value};
}
return null;
}
public static void main(String[] args) {
String parameters = "param1=HUvguys83789r8====";
System.out.println(Arrays.toString(splitParam(parameters)));
}
Output is
[param1, HUvguys83789r8====]
Just split once using the alternate version of split():
String[] strings = parameters.split("=", 2); // specify max 2 parts
Test code:
String parameters = "param1=HUvguys83789r8====";
String[] strings = parameters.split("=",2);
System.out.println(Arrays.toString(strings));
Output:
[param1, HUvguys83789r8====]
i think you need :
String parameters = "param1=HUvguys83789r8====";
String[] string = parameters.split("\\w=\\w");
String part1 = string[0]; // param
String part2 = string[1]; // Uvguys83789r8====
System.out.println(part1);
System.out.println(part2);
make sure to escape the slashes to make it java compliant
I have some expression in a Java string and a would get the letter, which was on the left side and on the right side of a specific sign.
Here are two examples:
X-Y
X-V-Y
Now, I need to extract in the first example the letter X and Y in a separate string. And in the second example, I need to extract the letters X, V and Y in a separate string.
How can i implemented this requirement in Java?
Try with:
String input = "X-V-Y";
String[] output = input.split("-"); // array with: "X", "V", "Y"
use String.split method with "-" token
String input = "X-Y-V"
String[] output = input.split("-");
now in the output array there will be 3 elements X,Y,V
String[] results = string.split("-");
do like this
String input ="X-V-Y";
String[] arr=input.split("-");
output
arr[0]-->X
arr[1]-->V
arr[2]-->Y
I'm getting in on this too!
String[] terms = str.split("\\W"); // split on non-word chars
You can use this method :
public String[] splitWordWithHyphen(String input) {
return input.split("-");
}
you can extract and handle a string by using the following code:
String input = "x-v-y";
String[] extractedInput = intput.split("-");
for (int i = 0; i < extractedInput.length - 1; i++) {
System.out.print(exctractedInput[i]);
}
Output: xvy
Example: Suppose, String contains (AA, BB, CC) then out put should be 3. Can some one tell how to get this result.
I tried like this
String userValues= "AA,BB,CC"
int selecteditems=userValues.length();
But I didnt get the result as 3.
userValues.split(",").length
this should do the trick
You should use String#split:
String[] splitted = userValues.split(",");
int selectedItems = splitted.length;
Tip: Always refer to the docs and see what they have to say, this will save for you a lot of efforts and time.
Personally I don't like the solutions that create a temporary string array then evaluates the array length, as doing all that is expensive in terms of performance.
Use this instead if performance matters
int num = 0;
for (int i = 0;
i < userValues.length();
num += (userValues.charAt(i++) == ',' ? 1 : 0));
/* num holds the occurrences */
But I agree that the solution [acknowledge Ameoo]
userValues.split(",").length
is clearer.
You can use String#split()
String[] separatedValues = userValues.split(",");
int selecteditems = separatedValues.length;
String userValues= "AA,BB,CC"
String x[]=userValues.split(",");
System.out.println(x.length);
output
3
String[] splitedArray = userValues.split(",");
int count = splitedArray.length; //remenber length not length()
Here is java doc split
public String[] split(String regex)
Splits this string around matches of the given regular expression.
You should first split the string by comma character.
String[] split= userValues.split(",");
Then just get the length of split array using
int len = split.length
If values are separated by comma,
then you could use
string.split(",");
and then get length
The other responses suggest splitting the string. This is fine for short strings, but will use more memory than necessary which could have a performance impact if you're processing long strings. An alternative is to use a regex to match the components of the string you want to count:
String s = "AA,BB,CC";
Pattern p = Pattern.compile( "([A-Z]+,?)" );
int count = 0, i = 0;
Matcher m = p.matcher( s );
while (m.find( i )) {
count++;
i = m.end();
}
System.out.println( count );
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