Here's a bit of a curly one I'm having trouble getting my head around. Say I have a string like this: "blah1***blah2****"
I want to convert it to a string as follows:
"blah1<3 stars>blah2<4stars>"
Anyone got any thoughts on how I'd do it? There could be anywhere from 1 to 100 stars in any given block. Without going into the semantics of why I need to do it, it's not a proposition to just order the data differently. I need to be able to make a conversion as outlined.
There are various ways: for example, split the string around *, and review each item of the list while keeping track of the number of {} in the list. Or split the string into a list of single characters and review each character.
Another way is to scan out substrings with and without *'s and upon each scan remove the scanned substring from the string. See below.
#---------------------------------------------------------------------
# countstars
# On input a string, returns a string with the ***'s replaced by
# <# stars>
#---------------------------------------------------------------------
proc countstars { string } {
set newstring {}
while { $string != "" } {
# substring without stars?
if {[scan $string {%[^*]} substring] == 1 } {
append newstring $substring
set sublength [string length $substring]
set string [string range $string $sublength end]
}
# substring with stars?
if {[scan $string {%[*]} substring] == 1 } {
set starcount [string length $substring]
switch -- $starcount {
1 { append newstring "<1 star>" }
default { append newstring "<$starcount stars>" }
}
set string [string range $string $starcount end]
}
}
return $newstring
}
# for testing purposes only
set string {This hotel has *****, but it is not even worth * or **}
puts "B: $string!"
puts "A: [countstars $string]!"
<font size=-1>[ This Message was edited by: egghead on 2002-04-01 11:00 ]</font>
Ahh, thanks egghead, gave me some ideas I havent used the switch command yet so I'm still reading through your example, but it has me thinking. I had a "writers block" on this one