Home > Blockchain >  Had to search whether the substring are present in the strings or not
Had to search whether the substring are present in the strings or not

Time:03-15

I have a few substrings to search in the below following strings

These are the substrings "School, Students, Teachers, Classrooms"

Below are the strings here I have the search whether the above substrings are present in the below strings-

School_Name
Number_Of_Students
Number_Of_Teachers
Number_Of_Classrooms

I have tried in this way, here in the string I have Students, Teachers, Classrooms substrings present, but I'm not able to search it properly

#!/usr/bin/tclsh
set list {School Students Teachers Classrooms}
set string "Number_Of_Students Number_Of_Teachers Number_Of_Classrooms"
if {"$string" in $list} {
puts "$string"
}

Can anyone help me out

CodePudding user response:

The in operator only does exact matching of a string against elements of a list. You probably want to use lsearch with a string match-style glob pattern; they're fairly easy to work with. Or maybe just string match and some foreach loops; I'm not sure what are the list of patterns and what are the list that is the search space.

# Added extra item to show what happens with multiple matches
set inputs {
    School_Name
    Number_Of_Students
    Number_Of_Teachers
    Number_Of_Classrooms
    Students_Per_School
}
set items {School Students Teachers Classrooms}
foreach input $inputs {
    foreach item $items {
        if {[string match *$item* $input]} {
            puts "found $item in $input"
        }
    }
}
  • Related