From Test-Scratch-Wiki

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 oinly 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 v] of [chars v]
set [i v] to [1]
repeat (length of (str 1))
add (letter (i) of (str 1)) to [chars v]
change [i v] by (1)
end
set [differences v] to [] //will contain all unshared characters
set [i v] to (1)
repeat (length of (str 2))
if <not <[chars v] contains (letter (i) of (str 2))>>
set [differences v] to (join (differences) (letter (i) of (str 2)))
change [i v] by (1)
end
end

Compiling the Similarities

Programming a variable that reports the similarities in two strings is only slightly changed.

define compare similarities of [str 1] to [str 2]
delete [all v] of [chars v]
set [i v] to [1]
repeat (length of (str 1))
add (letter (i) of (str 1)) to [chars v]
change [i v] by (1)
end
set [similarities v] to [] //will contain all shared characters
set [i v] to (1)
repeat (length of (str 2))
if <[chars v] contains (letter (i) of (str 2))> // this is the change
set [similarities v] to (join (similarities) (letter (i) of (str 2)))
change [i v] by (1)
end
end
Cookies help us deliver our services. By using our services, you agree to our use of cookies.