Don't say, “null String”, except possibly for this:- "null". Do you mean to say you have a 0‑length String in a space‑delimited text file? You are probably better off searching for a csv file parser.. . . its use is discouraged in new code.
I put 5 additional spaces in and got a count of 22. I would use a Scanner, or read the line and split it into an array with split().jshell Welcome to JShell -- Version 14.0.1
| For an introduction type: /help intro
jshell> "KRE 2017 1 3 0 34 27 2017.005544 424.306 424.28 0 1 N 172 10 2954 F".split(" ").length
$1 ==> 17
jshell> "KRE 2017 1 3 0 34 27 2017.005544 424.306 424.28 0 1 N 172 10 2954 F".split(" ").length
$2 ==> 22
jshell> "KRE 2017 1 3 0 34 27 2017.005544 424.306 424.28 0 1 N 172 10 2954 F".split(" ")
$3 ==> String[22] { "KRE", "2017", "1", "3", "0", "34", "", "", "", "", "", "27", "2017.005544", "424.306", "424.28", "0", "1", "N", "172", "10", "2954", "F" }
That's a pleasureBeata Szabo-Takacs wrote:. . . Thank you . . . I tried "\\s" and it works now! . . .
Campbell Ritchie wrote:Try "\\s+" to split on whitespace (any positive number of characters).
Varuna Seneviratna
Yes, I do.Varuna Seneviratna wrote:. . . I think by a 0-length String you mean a String without even a space. . . .
Of course it is; the 0‑length String is implicitly and trivially a substring of every String object.It is not practically possible to have a 0-length String within a String . . .
As I used it, it only means anything in the context of a regular expression. It means 1, 2, 3, 4, 5... ∞ repetitions of the pattern shown before. As I showed it, it allows any amount of whitespace with a positive length. No, it doesn't mean to split on a 0‑length String.What is meant by "any positive number of characters"? . . .
No, it doesn't. It splits on one character. If you want to split on any positive number of characters, you need "\\s+". There is a good introduction to regular expressions in the Java™ Tutorials.. . . provided that the "\\s" splits on any positive number of characters . . .
Why are you using StringTokenizer? It has been marked as legacy code for eighteen years. You have activated the option to add the delimiters back to the split Strings, which option String#split() doesn't have. StringTokenizer seems to use a different method for splitting, not using regular expressions.(Why aren't the delimiters displayed in the output of the above) . . .
Consider Paul's rocket mass heater. |