String matching: Difference between revisions

Content added Content deleted
(→‎{{header|C}}: Condensed in observation of the "Know thy standard library" commandment. Output fixed to put newlines at the end of lines.)
(CoffeeScript)
Line 266: Line 266:
user> (for [i evals] [i (eval i)])
user> (for [i evals] [i (eval i)])
([(. "abcd" startsWith "ab") true] [(. "abcd" endsWith "zn") false] [(. "abab" contains "bb") false] [(. "abab" contains "ab") true] [(. "abab" indexOf "bb") -1] [(let [loc (. "abab" indexOf "ab")] (. "abab" indexOf "ab" (dec loc))) 0])</lang>
([(. "abcd" startsWith "ab") true] [(. "abcd" endsWith "zn") false] [(. "abab" contains "bb") false] [(. "abab" contains "ab") true] [(. "abab" indexOf "bb") -1] [(let [loc (. "abab" indexOf "ab")] (. "abab" indexOf "ab" (dec loc))) 0])</lang>

=={{header|CoffeeScript}}==

This example uses string slices, but a better implementation might use indexOf for slightly better performance.

<lang coffeescript>
matchAt = (s, frag, i) ->
s[i...i+frag.length] == frag

startsWith = (s, frag) ->
matchAt s, frag, 0
endsWith = (s, frag) ->
matchAt s, frag, s.length - frag.length
matchLocations = (s, frag) ->
(i for i in [0..s.length - frag.length] when matchAt s, frag, i)
console.log startsWith "tacoloco", "taco" # true
console.log startsWith "taco", "tacoloco" # false
console.log startsWith "tacoloco", "talk" # false
console.log endsWith "tacoloco", "loco" # true
console.log endsWith "loco", "tacoloco" # false
console.log endsWith "tacoloco", "yoco" # false
console.log matchLocations "bababab", "bab" # [0,2,4]
console.log matchLocations "xxx", "x" # [0,1,2]
</lang>


=={{header|D}}==
=={{header|D}}==
Line 281: Line 308:
writeln([1,2,3].indexOf([2,3])) ; // 1
writeln([1,2,3].indexOf([2,3])) ; // 1
}</lang>
}</lang>

=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program CharacterMatching;
<lang Delphi>program CharacterMatching;