Comparing strings is the process of analyzing and outputting the differences or similarities between two strings. Comparing strings has many uses:
- Checking differences or similarities in a user response and the correct answer
- Analyzing the different responses from users inputted by Cloud Data on a form project
- Parsing lines of code
Compiling the Differences
Two variables may typically have differences in characters. For example, of variable 1 has a value of "potato" and variable 2 has a value of "tomato" the differences would be "pm" because those are the characters not shared by both variables. Only variable 1 contains a "p" and only variable 2 contains an "m". The following custom block analyzes the two strings specified by the block definition's parameters and compiled a variable of characters unshared between the two variables.
define compare differences of [str 1] to [str 2]
delete all of [chars v]
set [i v] to [1]
set [differencies v] to []
repeat (length of (str1))
add (letter (i) of (str1)) to [chars v]
change [i v] by (1)
end
set [i v] to [1]
repeat (length of (str2))
if <not <[chars v] contains (letter (i) of (str2)) ?>> then
set [j v] to [1]
set [match v] to [0]
repeat (length of (differencies))
if <(letter (j) of (differencies)) = (letter (i) of (str2))> then
set [match v] to [1]
end
change [j v] by (1)
end
if <(match) = [0]> then
set [differencies v] to (join (differencies) (letter (i) of (str2)))
end
end
change [i v] by (1)
end
delete all of [chars v]
set [i v] to [1]
repeat (length of (str2))
add (letter (i) of (str2)) to [chars v]
change [i v] by (1)
end
set [i v] to [1]
repeat (length of (str1))
if <not <[chars v] contains (letter (i) of (str1)) ?>> then
set [j v] to [1]
set [match v] to [0]
repeat (length of (differencies))
if <(letter (j) of (differencies)) = (letter (i) of (str1))> then
set [match v] to [1]
end
change [j v] by (1)
end
if <(match) = [0]> then
set [differencies v] to (join (differencies) (letter (i) of (str1)))
end
end
change [i v] by (1)
end
Compiling the Similarities
A script that reports the similarities in two strings is following:
define compare similarities of [str1] to [str2]
delete all of [chars v]
set [i v] to [1]
set [similarities v] to []
set [match v] to [0]
repeat (length of (str1))
add (letter (i) of (str1)) to [chars v]
change [i v] by (1)
end
set [i v] to [1]
repeat (length of (str2))
if <[chars v] contains (letter (i) of (str2)) ?> then
set [j v] to [1]
repeat (length of (similarities))
if <(letter (j) of (similarities)) = (letter (i) of (str2))> then
set [match v] to [1]
end
change [j v] by (1)
end
if <(match) = [0]> then
set [similarities v] to (join (similarities) (letter (i) of (str2)))
end
end
change [i v] by (1)
end