Removing everything after a certain char (IndexOfAny and Remove)
I have the following string array (quantityInForPriceBandPopUp[3]) data:
10 - 24
25 - 99
100 - 249
5000+
In C#, if I put this array through this:
quantityInForPriceBandPopUp[i] = quantityInForPriceBandPopUp[i]开发者_开发技巧.Remove(quantityInForPriceBandPopUp[i].IndexOfAny(new char[] { ' ', '+' }));
I get this:
10
25
100
5000
How do I reach the same result in Java? Ideally I am looking for a one line answer. If it is impossible, then the shortest would work.
There is no efficient one-line answer, because there is no direct equivalent to indexOfAny
in the java.lang.String
API.
Here's an efficient equivalent in a couple of lines.
int pos = Math.min(Math.max(s.indexOf(' '), -1), Math.max(s.indexOf('+'), -1));
if (pos != -1) {
s = s.substring(0, pos);
}
And you could easily turn that into a static helper method.
Have a look at http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringUtils.html
It has the indexOfAny method and many more string methods
Maybe not the most efficient, but you could use regular expressions and replaceFirst
for (int i = 0; i < arr.length; i++)
{
arr[i] = arr[i].replaceFirst("( |\\+).*$","");
}
Basically, it finds the first instance of either a space ' '
or plus sign +
, which we had to escape with two \
since +
is also a special symbol in regular expressions, along with any other characters following it .*
up to the end $
, and replaces it with an empty string.
If you needed to extend the code to catch other delimiters, like maybe .
, you just add the delimiter to the group with another |
operator:
arr[i] = arr[i].replaceFirst("( |\\+|\\.).*$","");
Now, this will compile a new regex Pattern each loop, which is definitely not ideal if you have a lot of Strings in your array. In that case, you might consider compiling a separate pattern first outside your loop:
Pattern pattern = Pattern.compile("( |\\+).*$");
for (int i = 0; i < arr.length; i++)
{
arr[i] = pattern.matcher(arr[i]).replaceFirst("");
}
If you want the parts afterwards, a regular expression like this would do:
for (int i = 0; i < arr.length; i++)
{
arr[i] = arr[i].replaceFirst("^.*( |\\+)\\s*","");
}
Note, this would need to be modified if you still want to capture "5000" for "5000+".
It may be worth your while to make a separate generic regex that uses "\d+" to locate numbers, like:
^(\\d+).*((\\d+)?)$
Then it's just a matter of using a Matcher and Matcher.group to pick out specific numbers.
Related links:
String documentation
Pattern documentation
Matcher documentation
Regular Expressions in Java
Wikipedia on Regular Expressions
精彩评论