String Difference

WJG (12/12/11) This simple proc arose out of the need to create text line references such as T08n0224_p0425a18(02)-T08n0224_p0425a19(00) in a more compact form, i.e T08n0224_p0425a18(02)-9(00).

#---------------
# Compare str2 to str1 until a mismatch is found. At that point return remainder of str2.
#---------------
# Arguments
#   str1   base string
#   str2   string to be compared
# Returns
#   The difference in string endings.
proc string_diff {str1 str2} {
    for {set i 0} {$i < [string length $str1]} {incr i} {
        if {[string index $str2 $i] ne [string index $str1 $i]} {
            return [string range $str2 $i end]
        }
    }
    return [string range $str2 $i end]
}

WJG (19/06/21) Almost ten years later and I've returned to this issue for a different (sorry about the pun) reason. This time, choose between characters or words.

## Compare 2 strings, return the portion where they differ
# @param[in] opt   Set to 'word' to compare word by word, else compare by character.
# @param[in] str1  Comparator String.
# @param[in] str2  The compared string. That is, compare str2 to str1.
# @returns The differences between the two strings.

proc string_diff { opt str1 str2 } {
        
        set div ""
        set cmd append
        if { $opt == "word" } { set div " " ; set cmd lappend }
        
        set res ""
        foreach c1 [split $str1 $div] c2 [split $str2 $div] {
                if { $c1 != $c2 } {
                        $cmd res $c2 
                }
        }
        return $res
}