Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

count number of spaces...  RSS feed

 
Brandi Love
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there some sort of a command that will cound the amount of space in between strings? I'm using a tokenizer to extract strings from a line in a file and I want to keep something of a column count, that gives the placement of the string within the line.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting problem awright. A few ideas...
Convert your string to char array and inspect one character at a time. Build up consecutive non-blanks into words, count consecutive blanks or just save the index at the start of each word. Sounds a little finicky.
If you have JDK 1.4 or later, look into the Pattern and Match classes and regular expressions. You might be able to put blanks into a group that you can retrieve and inspect. I can't swear that will work. Ask for details if it made no sense.
Use tokenizer to get all the words, then use indexOf to get the starting point of each word in the big string. Be careful to use the "from" option in indexOf so you don't confuse words with each other.
Do any of those ideas sing to you?
 
Tom Wolve
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
if you're using a StringTokenizer with ' ' as delimiter character, use it with returnDelims enabled.
Count all tokens which are equal to " " and that should do it.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
D'oh! Excellent! I have forgotten that one at some expense before. Shame on me!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!