|
|
|
|
Written by Aminur Rashid
|
|
Sunday, 25 March 2012 |
Post JDK 1.6, the new utility in String class reads as isEmpty(). If String is empty, can it contains(CharSequence ch) another String.
Answer is YES.
static void emptyContainer(String s1, String s2) {
if (s1.isEmpty()) {
assert !(s1.contains(s2));
}
}
Now that made me revisit the code to find number of occurrence of a sub String inside a parent String.
At a considerable amount of forums, the code variant as follows :
public static int countSubstringV1(String mainString, String subStr) {
int lastIndex = 0;
int count = 0;
while ((lastIndex = mainString.indexOf(subStr, lastIndex)) != -1) {
count++;
lastIndex += subStr.length();
}
//or
public static int countSubstringV2(String mainString, String subStr){
int ans = 0;
Matcher m = Pattern.compile(Pattern.quote(subStr)).matcher(mainString);
while (m.find())
ans++;//count it
return ans;
}
More variations at rosettacode. Try the two methods above passing "Aminur","" as two arguments. First one goes in an endless loop while second one returns mainSting.length()+1.
So its better idea, to check for empty String as well, along with its null check. Specially when conditions require dependency on contains() or e.g indexOf(...).
BTW, if you are going to provide a check in countSubstring method above e.g if(subStr.isEmpty()){..} what will be your return value? 0?mainString.length()?IllegalArgumentException?
Be first to comment this article
  
Add as favourites (13) | Quote this article on your site | Views: 156 | E-mail |
|
Last Updated ( Sunday, 25 March 2012 )
|
| |
|
|
Written by Aminur Rashid
|
|
Tuesday, 12 April 2011 |
Recently I was asked by one of our team mate that during load testing, order creation was failing (One of the application I am working on is an Order Management Application) because of wrong inputs. However, the unit tests, with the same input was working fine. Investigation into it, led to (once again) an old jdk "designed" bug 4146524 (or feature). After seeing such issues in a number of applications, I am sure a number of developers are yet not aware of Format objects are not thread-safe. So if you create a Format object (or a MessageFormat, NumberFormat, DecimalFormat, ChoiceFormat, DateFormat or SimpleDateFormat object), it cannot be shared among threads.
Be first to comment this article
  
Add as favourites (54) | Quote this article on your site | Views: 2611 | E-mail |
|
Last Updated ( Tuesday, 12 April 2011 )
|
|
Read more...
|
|
|
|
<< Start < Prev 1 2 Next > End >>
|
| Results 1 - 9 of 16 |