András Hummer
András Hummer

Reputation: 972

Can StringTokenizer countTokens ever be zero?

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

Answers (3)

Adam Siemion
Adam Siemion

Reputation: 16039

Below return 0:

  • new StringTokenizer("", "|").countTokens()
  • new StringTokenizer("|", "|").countTokens()
  • new StringTokenizer("||||", "|").countTokens()

so countTokens() returns 0 when:

  • the String is empty
  • the String contains only the delimeter

Upvotes: 3

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

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

JREN
JREN

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

Related Questions