Anil
Anil

Reputation: 1

I have a string, need that string to be compared with list of strings in TCL

Need to compare string1 with string2 in TCL

set string1 {laptop Keyboard mouse MONITOR PRINTER}
set string2 {mouse}

Upvotes: 0

Views: 763

Answers (2)

glenn jackman
glenn jackman

Reputation: 246754

There is string first

if {[string first $string2 $string1] != -1} {
    puts "string1 contains string2"
}

or

if {[string match *$string2* $string1]} {
    puts "string1 contains string2"
}

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137567

Well, you can use:

if {$string2 in $string1} {
    puts "present in the list"
}

Or you can use lsearch if you want to know where (it returns the index that it finds the element at, or -1 if it isn't there). This is most useful when you want to know where in the list the value is. It also has options to do binary searching (if you know the list is sorted) which is far faster than a linear search.

set idx [lsearch -exact $string1 $string2]
if {$idx >= 0} {
    puts "present in the list at index $idx"
}

But if you are doing a lot of searching, it can be best to create a hash table using an array or a dictionary. Those are extremely fast but require some setup. Whether the setup costs are worth it depends on your application.

set words {}
foreach word $string1 {dict set words $word 1}
if {[dict exists $words $string2]} {
    puts "word is present"
}

Note that if you're dealing with ordinary user input, you probably want a sanitization step or two. Tcl lists aren't exactly sentences, and the differences can really catch you out once you move to production. The two main tools for that are split and regexp -all -inline.

set words [split $sentence]
set words [regexp -all -inline {\S+} $sentence]

Understanding how to do the cleanup requires understanding your input data more completely than I do.

Upvotes: 1

Related Questions