String matching: Difference between revisions

Line 1,962:
R_find: 0 1 6 Nil()
R_find_all: 0 1 3 5 6 Nil() </pre>
 
=={{header|Phix}}==
<lang Phix>constant word = "the", -- (also try this with "th"/"he")
sentence = "the last thing the man said was the"
-- sentence = "thelastthingthemansaidwasthe" -- (practically the same results)
 
-- A common, but potentially inefficient idiom for checking for a substring at the start is:
if match(word,sentence)=1 then
?"yes(1)"
end if
-- A more efficient method is to test the appropriate slice
if length(sentence)>=length(word)
and sentence[1..length(word)]=word then
?"yes(2)"
end if
-- Which is almost identical to checking for a word at the end
if length(sentence)>=length(word)
and sentence[-length(word)..-1]=word then
?"yes(3)"
end if
-- Or sometimes you will see this, a tiny bit more efficient:
if length(sentence)>=length(word)
and match(word,sentence,length(sentence)-length(word)+1) then
?"yes(4)"
end if
-- Finding all occurences is a snap:
integer r = match(word,sentence)
while r!=0 do
?r
r = match(word,sentence,r+1)
end while</lang>
{{out}}
<pre>
"yes(1)"
"yes(2)"
"yes(3)"
"yes(4)"
1
16
33
</pre>
 
=={{header|PHP}}==
7,820

edits