There's no straight forward functions that you can use to get such a percentage, but different functions to help you achieve that.
If the two strings have words separated by a dot, comma or just space you would need to turn the string into a list by splitting them by that element, in your case that dot. We achieve this by using the
split function.
Code: Select all
set texta [split $texta .]
set textb [split $textb .]
Next to to see how many elements of the first list (texta) are in the second (textb) you have to loop tough all the elements of the list and check if they are present in the second.
We achieve this by using
foreach to loop,
lsearch to see if a element is in a list and by using
incr will be incrementing the
count variable when a match was found.
Code: Select all
set count 0
foreach ele $texta {
if {[lsearch -nocase $textb $ele] != -1} {
incr count
}
}
The
-nocase option tells the lsearch function to ignore the lower, upper or mixed case of the characters of the "element" (or simply put word) when doing the match search.
After the
foreach loop has finished you will have in $count the total number of matches it found. Notice the lack of $ in front of the count at the incr line. There's no need for it there, but when you want to see it's value you would need that dollar sign in front of it.
If you want to see how long is the second list and how many of the words it matched then you could use
llength to get it's length and expr to do the math calculation of the exact percentage.
Code: Select all
set size [llength $textb]
set percentage [expr $count*100/$size]
So now in $percentage you got exactly how much the first string matches the second, in your case it's a 75% match.
Something worth checking:
lists and
strings
Edit: After a bit of thinking I've come with a different approach that's a bit more straight forward than the above method by using
lmap, but would still need to split those two strings.
Code: Select all
set texta [split $texta .]
set textb [split $textb .]
set matches [lmap x $texta {expr {[lsearch -nocase $textb $x] !=1 ? $x : [continue]}}]
Now $matches would contain the elements that are common to the two strings and from here can just get the size of the second list (after splitting the second string) and the size of the matches list then do the math to get percentage.
Code: Select all
set size [llength $textb]
set count [llength $matches]
set percentage [expr $count*100/$size]
If you want to stick with the first approach and get the matches inside a variable then we add the
lappend to the
foreach loop list this.
Code: Select all
set matches [list]
foreach ele $texta {
if {[lsearch -nocase $textb $ele] != -1} {
incr count
lappend matches $ele
}
}
Notice that we first need to define the matches variable prior to using it, hence the line on top of the start of the
foreach loop.
If you got any questions don't hesitate to ask.
Once the game is over, the king and the pawn go back in the same box.