Reputation: 972
I just found a piece of Java code inside a method:
if (param.contains("|")) {
StringTokenizer st = new StringTokenizer(param.toLowerCase().replace(" ", ""), "|");
if (st.countTokens() > 0) {
...
}
} else {
return myString.contains(param);
}
Can countTokens
in the above case ever be less than 1?
Upvotes: 0
Views: 1518
Reputation: 16039
Below return 0
:
new StringTokenizer("", "|").countTokens()
new StringTokenizer("|", "|").countTokens()
new StringTokenizer("||||", "|").countTokens()
so countTokens()
returns 0
when:
String
is emptyString
contains only the delimeterUpvotes: 3
Reputation: 35577
Look at this
String param="";
StringTokenizer st = new StringTokenizer(param.toLowerCase().replace(" ", ""), "|");
System.out.println(st.countTokens());
answer is 0(zero)
Upvotes: 1
Reputation: 3630
It can, if the string you're trying to tokenize is empty, otherwise it'll always at least be 1
Example 1:
String myStr = "abcdefg";
StringTokenizer st = new StringTokenizer(myStr, ";");
int tokens = st.countTokens();
System.out.println("Number of tokens: " + tokens);
> "Number of tokens: 1"
Example 2:
String myStr = "";
StringTokenizer st = new StringTokenizer(myStr, ";");
int tokens = st.countTokens();
System.out.println("Number of tokens: " + tokens);
> "Number of tokens: 0"
Example 3:
String myStr = "abc;defg";
StringTokenizer st = new StringTokenizer(myStr, ";");
int tokens = st.countTokens();
System.out.println("Number of tokens: " + tokens);
> "Number of tokens: 2"
Upvotes: 5