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 );
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 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()});
I am having a hard time figuring with out. Say I have String like this
String s could equal
s = "{1,4,204,3}"
at another time it could equal
s = "&5,3,5,20&"
or it could equal at another time
s = "/4,2,41,23/"
Is there any way I could just extract the numbers out of this string and make a char array for example?
You can use regex for this sample:
String s = "&5,3,5,20&";
System.out.println(s.replaceAll("[^0-9,]", ""));
result:
5,3,5,20
It will replace all the non word except numbers and commas. If you want to extract all the number you can just call split method -> String [] sArray = s.split(","); and iterate to all the array to extract all the number between commas.
You can use RegEx and extract all the digits from the string.
stringWithOnlyNumbers = str.replaceAll("[^\\d,]+","");
After this you can use split() using deliminator ',' to get the numbers in an array.
I think split() with replace() must help you with that
Use regular expressions
String a = "asdf4sdf5323ki";
String regex = "([0-9]*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(a);
while (matcher.find())
{
String group = matcher.group(1);
if (group.length() > 0)
{
System.out.println(group);
}
}
from your cases, if the pattern of string is same in all cases, then something like below would work, check for any exceptions, not mentioned here :
String[] sArr= s.split(",");
sArr[0] = sArr[0].substring(1);
sArr[sArr.length()-1] =sArr[sArr.length()-1].substring(0,sArr[sArr.length()-1].length()-1);
then convert the String[] to char[] , here is an example converter method
You can use Scanner class with , delimiter
String s = "{1,4,204,3}";
Scanner in = new Scanner(s.substring(1, s.length() - 1)); // Will scan the 1,4,204,3 part
in.useDelimiter(",");
while(in.hasNextInt()){
int x = in.nextInt();
System.out.print(x + " ");
// do something with x
}
The above will print:
1 4 204 3
I need to extract several integers from a string that looks like this:
22:43:12:45
I need to extract 22, 43, 12, and 45 as separate integers. I need to use string methods or scanner methods to read up until : and extract the 22. Then read between the first : and second : to give me 43, and so on.
I can extract up to the first : no problem, but I down know what to do thereafter.
Any help would be much appreciated.
String[] parts = str.split(":");
int[] numbers = new int[parts.length];
Iterate over this String array to get an array of integers:
int index = 0;
for(String part : parts)
numbers[index++] = Integer.parseInt(part);
You should look at String.split method . Given a regular expression, this methods splits the string based on that. In your case the regular expression is a ":"
String s ="22:43:12:45";
int i =0;
for (String s1 : s.split(":")) { // For each string in the resulting split array
i = Integer.parseInt(s1);
System.out.println(i);
}
The split returns a string array with your string separated. So in this case , The resulting string array will have "22" on the 0th position, "43" on the first position and so on. To convert these to integers you can use the parseInt method which takes in a string and gives the int equivalent.
You can use only indexOf and substring methods of String:
String text = "22:43:12:45";
int start = 0;
int colon;
while (start < text.length()) {
colon = text.indexOf(':', start);
if (colon < 0) {
colon = text.length();
}
// You can store the returned value somewhere, in a list for example
Integer.parseInt(text.substring(start, colon)));
start = colon + 1;
};
Using Scanner is even simpler:
String text = "22:43:12:45";
Scanner scanner = new Scanner(text);
scanner.useDelimiter(":");
while (scanner.hasNext()) {
// Store the returned value somewhere to use it
scanner.nextInt();
}
However, String.split is the shortest solution.
Make a regex like
(\d\d):(\d\d):(\d\d):(\d\d)
So let's say I have:
String string1 = "123,234,345,456,567*nonImportantData";
String[] stringArray = string1.split(", ");
String[] lastPart = stringArray[stringArray.length-1].split("*");
stringArray[stringArray.length-1] = lastPart[0];
Is there any easier way of making this code work? My objective is to get all the numbers separated, whether stringArray includes nonImportantData or not. Should I maybe use the substring method?
Actually, the String.split(...) method's argument is not a separator string but a regular expression.
You can use
String[] splitStr = string1.split(",|\\*");
where | is a regexp OR and \\ is used to escape * as it is a special operator in regexp. Your split("*") would actually throw a java.util.regex.PatternSyntaxException.
Assuming you always have the format you've provided....
String input = "123,234,345,456,567*nonImportantData";
String[] numbers = input.split("\\*")[0].split(",");
I'd probably remove the unimportant data before splitting the string.
int idx = string1.indexOf('*');
if (idx >= 0)
string1 = string1.substring(0, idx);
String[] arr = string1.split(", ");
If '*' is always present, you can shorten it like this:
String[] arr = str.substring(0, str.indexOf('*')).split(", ");
This is different than MarianP's approach because the "unimportant data" isn't preserved as an element of the array. This may or may not be helpful, depending on your application.