String matching: Difference between revisions
Add ed example
Thundergnat (talk | contribs) m (→{{header|Icon}} and {{header|Unicon}}: Regularize non-standard header markup) |
(Add ed example) |
||
(47 intermediate revisions by 37 users not shown) | |||
Line 19:
{{Template:Strings}}
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">print(‘abcd’.starts_with(‘ab’))
print(‘abcd’.ends_with(‘zn’))
print(‘bb’ C ‘abab’)
print(‘ab’ C ‘abab’)
print(‘abab’.find(‘bb’) ? -1)
print(‘abab’.find(‘ab’) ? -1)</syntaxhighlight>
{{out}}
<pre>
1B
0B
0B
1B
-1
0
</pre>
=={{header|360 Assembly}}==
<
STRMATCH CSECT
USING STRMATCH,R15
Line 54 ⟶ 74:
PG DC CL80' '
YREGS
END STRMATCH</
{{out}}
<pre>
Line 65 ⟶ 85:
CD
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program strMatching64.s */
Line 318 ⟶ 339:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC FindS(CHAR ARRAY text,sub BYTE start)
BYTE i,j,found
i=start
WHILE i<=text(0)-sub(0)+1
DO
found=0
FOR j=1 TO sub(0)
DO
IF text(i+j-1)#sub(j) THEN
found=0 EXIT
ELSE
found=1
FI
OD
IF found THEN
RETURN (i)
FI
i==+1
OD
RETURN (0)
BYTE FUNC StartsWith(CHAR ARRAY text,sub)
BYTE pos
pos=FindS(text,sub,1)
IF pos=1 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC EndsWith(CHAR ARRAY text,sub)
BYTE pos,start
IF sub(0)>text(0) THEN
RETURN (0)
FI
start=text(0)-sub(0)+1
pos=FindS(text,sub,start)
IF pos=start THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC Contains(CHAR ARRAY text,sub
BYTE ARRAY positions)
BYTE pos,count
pos=1 count=0
WHILE pos<=text(0)
DO
pos=FindS(text,sub,pos)
IF pos>0 THEN
positions(count)=pos
count==+1
pos==+1
ELSE
EXIT
FI
OD
RETURN (count)
PROC TestStartsWith(CHAR ARRAY text,sub)
IF StartsWith(text,sub) THEN
PrintF("""%S"" starts with ""%S"".%E",text,sub)
ELSE
PrintF("""%S"" does not start with ""%S"".%E",text,sub)
FI
RETURN
PROC TestEndsWith(CHAR ARRAY text,sub)
IF EndsWith(text,sub) THEN
PrintF("""%S"" ends with ""%S"".%E",text,sub)
ELSE
PrintF("""%S"" does not end with ""%S"".%E",text,sub)
FI
RETURN
PROC TestContains(CHAR ARRAY text,sub)
BYTE ARRAY positions(20)
BYTE i,count
count=Contains(text,sub,positions)
IF count>0 THEN
PrintF("""%S"" contains %B ""%S"" at positions:",text,count,sub)
FOR i=0 TO count-1
DO
PrintB(positions(i))
IF i<count-1 THEN
Print(", ")
ELSE
PrintE(".")
FI
OD
ELSE
PrintF("""%S"" does not contain ""%S"".%E",text,sub)
FI
RETURN
PROC Main()
TestStartsWith("1234abc","123")
TestStartsWith("1234abc","234")
PutE()
TestContains("abbaabab","ab")
TestContains("abbaabab","ba")
TestContains("abbaabab","xyz")
PutE()
TestEndsWith("1234abc","abc")
TestEndsWith("1234abc","ab")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_matching.png Screenshot from Atari 8-bit computer]
<pre>
"1234abc" starts with "123".
"1234abc" does not start with "234".
"abbaabab" contains 3 "ab" at positions:1, 5, 7.
"abbaabab" contains 2 "ba" at positions:3, 6.
"abbaabab" does not contain "xyz".
"1234abc" ends with "abc".
"1234abc" does not end with "ab".
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
Line 341 ⟶ 487:
);
end Match_Strings;
</syntaxhighlight>
{{out}}
<pre>
Line 351 ⟶ 497:
=={{header|Aime}}==
<
data b;
Line 372 ⟶ 518:
o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b.seek(t) == 0,
b.seek(t) != -1,
b.seek(t) != -1 && b.seek(t) + ~t == ~b);</
{{out}}
<pre>starts with, embeds, ends with "Bang": 1, 1, 0
Line 383 ⟶ 529:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - string in string is non-standard?}}
<
PRIO STARTSWITH = 5, ENDSWITH = 5;
OP STARTSWITH = (STRING str, prefix)BOOL: # assuming LWB = 1 #
Line 400 ⟶ 546:
(string in string("ab",loc,"abab")|loc|-1), # returns +1 #
(string in string("ab",loc2,"abab"[loc+1:])|loc+loc2|-1) # returns +3 #
))</
{{out}}
<pre>
Line 407 ⟶ 553:
=={{header|AppleScript}}==
<
set string1 to "I felt happy"
Line 423 ⟶ 569:
-- Print the location of the match for part 2
offset of string2 in stringA --> 69</
AppleScript doesn't have a builtin means of matching multiple occurrences of a substring, however one can redefine the existing '''offset''' command to add this functionality:
<
on offset of needle in haystack
local needle, haystack
Line 447 ⟶ 593:
end offset
offset of "happy" in stringA --> {8, 44, 83, 110}</
or, defining an '''offsets''' function in terms of a more general '''findIndices''':
<
on offsets(needle, haystack)
script match
Line 520 ⟶ 666:
end script
end if
end mReturn</
{{Out}}
<pre>{8, 44, 83, 110}</pre>
Line 526 ⟶ 672:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program strMatching.s */
Line 768 ⟶ 914:
bx lr @ return
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">print prefix? "abcd" "ab"
print prefix? "abcd" "cd"
print suffix? "abcd" "ab"
print suffix? "abcd" "cd"
print contains? "abcd" "xy"
print
print
print
print index "abcd" "xy"</syntaxhighlight>
{{out}}
<pre>
false
false
true
true
false
true
false
1
null</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
String1 = abcd
String2 = abab
Line 802 ⟶ 960:
If TempVar = %String2%
MsgBox, "%String1%" ends with "%String2%".
</syntaxhighlight>
=={{header|AutoIt}}==
<
$string2 = "ard"
Line 835 ⟶ 993:
EndIf
</syntaxhighlight>
=={{header|AWK}}==
<
{ pos=index($2,$1)
print $2, (pos==1 ? "begins" : "does not begin" ), "with " $1
print $2, (pos ? "contains an" : "does not contain" ), "\"" $1 "\""
if (pos) {
l=length($1)
Pos=pos
s=$2
x+=Pos
s=substr(s,Pos+l)
Pos=index(s,$1)
}
}
print $2, (substr($2,pos)==$1
}
</syntaxhighlight>
=={{header|BASIC}}==
{{works with|QBasic}}
<
'Determining if the first string starts with second string
Line 890 ⟶ 1,045:
END IF
</syntaxhighlight>
{{out}}
Line 898 ⟶ 1,053:
==={{header|Applesoft BASIC}}===
<
20 S$ = "TH"
30 DEF FN S(P) = MID$(A$, P, LEN(S$)) = S$
Line 915 ⟶ 1,070:
310 E$(1) = "ENDS"
320 E$(0) = "DOES NOT END"
330 PRINT E$(FN S(LEN(A$) - LEN(S$) + 1))" WITH "S$</
=={{header|Batch File}}==
<
::you put some of the CMD special characters (ex. %,!, etc) inside the strings.
::
Line 987 ⟶ 1,142:
set /a length+=1
goto loop
::/The functions.</
{{out}}
<pre>"qwertyuiop" begins with "qwerty".
Line 1,001 ⟶ 1,156:
=={{header|BBC BASIC}}==
<
FOR test% = 1 TO 3
Line 1,033 ⟶ 1,188:
UNTIL I% = 0
= N%
</syntaxhighlight>
{{out}}
<pre>"The fox jumps over the dog" starts with "The"
Line 1,043 ⟶ 1,198:
"The fox jumps over the dog" contains "dog" at position 24
"The fox jumps over the dog" contains "dog" 1 time(s)</pre>
=={{header|BQN}}==
<code>⍷</code> does much of the heavy lifting here. It is commuted with <code>˜</code> so the order of the arguments makes sense.
<syntaxhighlight lang="bqn">SW ← ⊑⍷˜
Contains ← ∨´⍷˜
EW ← ¯1⊑⍷˜
Locs ← /⍷˜</syntaxhighlight>
{{Out|Usage}}
<syntaxhighlight lang="bqn"> "abcd" SW "ab"
1
"abcd" SW "cd"
0
"abcd" EW "ab"
0
"abcd" EW "cd"
1
"abcd" Contains "bb"
0
"abcd" Contains "ab"
1
"abcd" Contains "bc"
1
"abab" Contains "ab"
1
"abab" Locs "ab"
⟨ 0 2 ⟩</syntaxhighlight>
=={{header|Bracmat}}==
Bracmat does pattern matching in expressions <code><i>subject</i>:<i>pattern</i></code> and in strings <code>@(<i>subject</i>:<i>pattern</i>)</code>. The (sub)pattern <code>?</code> is a wild card.
<
& out$(@(!sentence:I ?) & "sentence starts with 'I'" | "sentence does not start with 'I'")
& out$(@(!sentence:? such ?) & "sentence contains 'such'" | "sentence does not contain 'such'")
Line 1,054 ⟶ 1,239:
| out$str$("sentence contains " !N " occurrences of 'be'")
)
)</
In the last line, Bracmat is forced by the always failing node <code>~</code> to backtrack until all occurrences of 'be' are found.
Thereafter the pattern match expression fails.
Line 1,068 ⟶ 1,253:
=={{header|C}}==
Case sensitive matching:
<
#include <stdio.h>
Line 1,099 ⟶ 1,284:
return 0;
}</
{{out}}
<pre>Starts with Test ( Hello,Hell ) : 1
Line 1,105 ⟶ 1,290:
Contains Test ( Google,msn ) : 0</pre>
Code without using string library to demonstrate how char strings are just pointers:
<
/* returns 0 if no match, 1 if matched, -1 if matched and at end */
Line 1,148 ⟶ 1,333:
return 0;
}</
{{out}}
<pre>matching `A Short String' with `ort S':
Line 1,165 ⟶ 1,350:
=={{header|C sharp|C#}}==
{{works with|Mono|2.6}}
<
class Program
{
Line 1,179 ⟶ 1,364:
}
}
</syntaxhighlight>
=={{header|C++}}==
<
using namespace std;
Line 1,195 ⟶ 1,380:
s1.find(s2)//returns string::npos
int loc=s2.find(s3)//returns 0
loc=s2.find(s3,loc+1)//returns 2</
=={{header|Clojure}}==
{{trans|Java}}
<
(. "abcd" endsWith "zn")
(. "abab" contains "bb")
Line 1,208 ⟶ 1,393:
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])</
=={{header|CoffeeScript}}==
Line 1,214 ⟶ 1,399:
This example uses string slices, but a better implementation might use indexOf for slightly better performance.
<
matchAt = (s, frag, i) ->
s[i...i+frag.length] == frag
Line 1,235 ⟶ 1,420:
console.log matchLocations "bababab", "bab" # [0,2,4]
console.log matchLocations "xxx", "x" # [0,1,2]
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(defun starts-with-p (str1 str2)
"Determine whether `str1` starts with `str2`"
Line 1,267 ⟶ 1,452:
(print (containsp "ababaBa" "ba")) ; (1 3)
(print (containsp "foobar" "x")) ; NIL
</syntaxhighlight>
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE StringMatch;
IMPORT StdLog,Strings;
Line 1,385 ⟶ 1,570:
END Do;
END StringMatch.
</syntaxhighlight>
Execute: ^Q StringMatching.Do <br/>
{{out}}
Line 1,410 ⟶ 1,595:
=={{header|D}}==
<
import std.stdio;
import std.algorithm: startsWith, endsWith, find, countUntil;
Line 1,425 ⟶ 1,610:
[1, 2, 3].countUntil(3).writeln; // 2
[1, 2, 3].countUntil([2, 3]).writeln; // 1
}</
{{out}}
<pre>true
Line 1,437 ⟶ 1,622:
=={{header|DCL}}==
<
$ length_of_first_string = f$length( first_string )
$ second_string = p2
Line 1,460 ⟶ 1,645:
$ else
$ write sys$output "first string does not end with the second string"
$ endif</
{{out}}
<pre>$ @string_matching efabcdef ef
Line 1,480 ⟶ 1,665:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,492 ⟶ 1,677:
Writeln(AnsiContainsText('abcd', 'ab')); // True
WriteLn(Pos('ab', 'abcd')); // 1
end.</
=={{header|Dyalect}}==
<
value = "abcd".
value = "abab".
value = "abab".
var loc = "abab".
loc = "abab".
=={{header|E}}==
<
println(string1.startsWith(string2))
Line 1,515 ⟶ 1,700:
println(string1.endsWith(string2))
}</
=={{header|EchoLisp}}==
<
(string-suffix? "nette" "Antoinette") → #t
(string-prefix? "Simon" "Simon & Garfunkel") → #t
Line 1,524 ⟶ 1,709:
(string-match "Antoinette" "net") → #t ;; contains
(string-index "net" "Antoinette") → 5 ;; substring location
</syntaxhighlight>
=={{header|EasyLang}}==
<syntaxhighlight>
func starts s$ t$ .
if substr s$ 1 len t$ = t$
return 1
.
return 0
.
func ends s$ t$ .
if substr s$ (len s$ - len t$ + 1) len t$ = t$
return 1
.
return 0
.
func contains s$ t$ .
return if strpos s$ t$ > 0
.
print starts "hello world" "he"
print ends "hello world" "rld"
print contains "hello world" "wor"
</syntaxhighlight>
=={{header|ed}}==
This script joins two strings (each on the line of its own) with vertical bar and then does regex matching against them.
<syntaxhighlight lang="sed">
H
s/^/|/
,j
t0
t0
1s/^(.*)(.*)\|\1$/String \1\2 starts with \1/
1s/^(.*)\|(.*)/String \1 does not start with \2/
2s/^(.*)(.*)(.*)\|\2$/String \1\2\3 contains \2/
2s/^(.*)\|(.*)/String \1 does not contain \2/
3s/^(.*)(.*)\|\2$/String \1\2 ends with \2/
3s/^(.*)\|(.*)/String \1 does not end with \2/
,p
Q
</syntaxhighlight>
{{out}}
<pre>$ cat string-matching.ed | ed -lEGs string-matching.input
String abab starts with ab
String abab contains ab
String abab ends with ab</pre>
=={{header|Elena}}==
ELENA
<
public program()
Line 1,534 ⟶ 1,769:
var s := "abcd";
console.printLine(s," starts with ab: ",s.startingWith
console.printLine(s," starts with cd: ",s.startingWith
console.printLine(s," ends with ab: ",s.endingWith
console.printLine(s," ends with cd: ",s.endingWith
console.printLine(s," contains ab: ",s.containing
console.printLine(s," contains bc: ",s.containing
console.printLine(s," contains cd: ",s.containing
console.printLine(s," contains az: ",s.containing
console.printLine(s," index of az: ",s.indexOf(0, "az"));
Line 1,551 ⟶ 1,786:
console.readChar()
}</
=={{header|Elixir}}==
The String module has functions that cover the base requirements.
<
s2 = "adab"
s3 = "ab"
Line 1,582 ⟶ 1,817:
Regex.scan(~r/#{s3}/, "abcabc", return: :index)
# => [[{0, 2}], [{3, 2}]]</
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun string-contains (needle haystack)
(string-match (regexp-quote needle) haystack))
(string-prefix-p "before" "before center after") ;=> t
(string-contains "before" "before center after") ;=> 0
(string-suffix-p "before" "before center after") ;=> nil
(string-prefix-p "center" "before center after") ;=> nil
(string-contains "center" "before center after") ;=> 7
(string-suffix-p "center" "before center after") ;=> nil
(
(string-contains "after" "before center after") ;=> 14
(string-suffix-p "after" "before center after") ;=> t</syntaxhighlight>
=={{header|Erlang}}==
<
-module(character_matching).
-export([starts_with/2,ends_with/2,contains/2]).
Line 1,661 ⟶ 1,865:
contains(_S1,_S2,_N,Acc) ->
Acc.
</syntaxhighlight>
=={{header|Euphoria}}==
<
integer x
Line 1,693 ⟶ 1,897:
else
printf(1, "'%s' does not end with '%s'\n", {first, second})
end if</
{{out}}
Line 1,702 ⟶ 1,906:
=={{header|F_Sharp|F#}}==
<
let main args =
Line 1,725 ⟶ 1,929:
if idx < 0 then None else Some (idx, idx+1)) 0
|> Seq.iter (printfn "substring %A begins at position %d (zero-based)" contains)
0</
{{out}}
<pre>text = "一二三四五六七八九十"
Line 1,741 ⟶ 1,945:
=={{header|Factor}}==
Does <code>cheesecake</code> start with <code>cheese</code>?
<
Does <code>cheesecake</code> contain <code>sec</code> at any location?
<
Does <code>cheesecake</code> end with <code>cake</code>?
<
Where in <code>cheesecake</code> is the leftmost <code>sec</code>?
<
Where in <code>Mississippi</code> are all occurrences of <code>iss</code>?
<
"Mississippi" "iss" <regexp> all-matching-slices [ from>> ] map ! { 1 4 }</
=={{header|Falcon}}==
'''VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems falconic''
<
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 1,769 ⟶ 1,973:
> s1.endsWith(s2) ? @ "s1 ends with $s2" : @ "$s1 does not end with $s2"
</syntaxhighlight>
{{out}}
<pre>
Line 1,790 ⟶ 1,994:
* <code>indexrIgnoreCase</code> (like above, ignoring case for ASCII characters)
<
class Main
{
Line 1,813 ⟶ 2,017:
}
}
</syntaxhighlight>
{{out}}
Line 1,831 ⟶ 2,035:
=={{header|FBSL}}==
<
DIM s = "roko, mat jane do"
Line 1,846 ⟶ 2,050:
WHILE INSTR(mane, match, INSTR + 1): PRINT " ", INSTR;: WEND
END SUB
</syntaxhighlight>
{{out}}
<pre>"roko, mat jane do" starts with "roko"
Line 1,856 ⟶ 2,060:
=={{header|Forth}}==
<
tuck 2>r min 2r> compare 0= ;
: ends-with ( a l a2 l2 -- ? )
tuck 2>r negate over + 0 max /string 2r> compare 0= ;
\ use SEARCH ( a l a2 l2 -- a3 l3 ? ) for contains</
=={{header|Fortran}}==
Line 1,869 ⟶ 2,073:
In the case of STARTS, these annoyances can be left to the INDEX function rather than comparing the start of A against B. At the cost of it searching the whole of A if B is not at the start. Otherwise, it would be the mirror of ENDS.
<syntaxhighlight lang="fortran">
SUBROUTINE STARTS(A,B) !Text A starts with text B?
CHARACTER*(*) A,B
Line 1,910 ⟶ 2,114:
CALL ENDS("Brief","Much longer")
END
</syntaxhighlight>
Output: text strings are bounded by >''etc.''< in case of leading or trailing spaces.
<pre>
Line 1,922 ⟶ 2,126:
Similar program using modern Fortran style
<syntaxhighlight lang="fortran">
!-----------------------------------------------------------------------
!Main program string_matching
Line 1,985 ⟶ 2,189:
end function ends
end program string_matching
</syntaxhighlight>
Output: false = 0, true = 1 ( + multiple occurrences if applicable)
<pre>
Line 2,000 ⟶ 2,204:
=={{header|FreeBASIC}}==
<
Dim As String s1 = "abracadabra"
Line 2,025 ⟶ 2,229:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,035 ⟶ 2,239:
First string contains second string : at index 1 and at index 8
First string ends with second string : true
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1, @"String matching", (0,0,650,360)
void local fn DoIt
CFStringRef s1, s2
CFRange range
s1 = @"alphabravocharlie"
s2 = @"alpha"
if ( fn StringHasPrefix( s1, s2 ) )
print @"\"";s1;@"\" starts with \"";s2;@"\""
else
print @"\"";s1;@"\" does not start with \"";s2;@"\""
end if
print
s2 = @"bravo"
if ( fn StringHasPrefix( s1, s2 ) )
print @"\"";s1;@"\" starts with \"";s2;@"\""
else
print @"\"";s1;@"\" does not start with \"";s2;@"\""
end if
print
range = fn StringRangeOfString( s1, s2 )
if ( range.location != NSNotFound )
print @"\"";s1;@"\" contains \"";s2;@"\" at location ";(range.location)
else
print @"\"";s1;@"\" does not contain \"";s2;@"\""
end if
print
s2 = @"delta"
range = fn StringRangeOfString( s1, s2 )
if ( range.location != NSNotFound )
print @"\"";s1;@"\" contains \"";s2;@"\" at location ";(range.location)
else
print @"\"";s1;@"\" does not contain \"";s2;@"\""
end if
print
s2 = @"charlie"
if ( fn StringHasSuffix( s1, s2 ) )
print @"\"";s1;@"\" ends with \"";s2;@"\""
else
print @"\"";s1;@"\" does not end with \"";s2;@"\""
end if
print
s2 = @"alpha"
if ( fn StringHasSuffix( s1, s2 ) )
print @"\"";s1;@"\" ends with \"";s2;@"\""
else
print @"\"";s1;@"\" does not end with \"";s2;@"\""
end if
print
s1 = @"alpha delta charlie delta echo delta futurebasic"
s2 = @"delta"
range = fn StringRangeOfString( s1, s2 )
while ( range.location != NSNotFound )
print @"\"";s1;@"\" contains \"";s2;@"\" at location ";(range.location)
range.location++
range = fn StringRangeOfStringWithOptionsInRange( s1, s2, 0, fn CFRangeMake( range.location, len(s1)-range.location ) )
wend
end fn
fn DoIt
HandleEvents</syntaxhighlight>
{{out}}
<pre>
"alphabravocharlie" starts with "alpha"
"alphabravocharlie" does not start with "bravo"
"alphabravocharlie" contains "bravo" at location 5
"alphabravocharlie" does not contain "delta"
"alphabravocharlie" ends with "charlie"
"alphabravocharlie" does not end with "alpha"
"alpha delta charlie delta echo delta futurebasic" contains "delta" at location 6
"alpha delta charlie delta echo delta futurebasic" contains "delta" at location 20
"alpha delta charlie delta echo delta futurebasic" contains "delta" at location 31
</pre>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=07bb32f4e8e8f7d81898cf41d4431a2e Click this link to run this code]'''
<
Dim sString1 As String = "Hello world"
Dim sString2 As String = "Hello"
Line 2,047 ⟶ 2,347:
Print sString1 Ends Left(sString2, 5) 'Determine if the first string ends with the second string
End</
Output:
<pre>
Line 2,054 ⟶ 2,354:
False
</pre>
=={{header|GDScript}}==
<syntaxhighlight lang="gdscript">
@tool
extends Node
@export var first_string: String
@export var second_string: String
@export var starts_with: bool:
get: return first_string.begins_with(second_string)
@export var contains: bool:
get: return first_string.contains(second_string)
@export var ends_with: bool:
get: return first_string.ends_with(second_string)
</syntaxhighlight>
=={{header|GML}}==
{{trans|BASIC}}
<
{
first = "qwertyuiop";
Line 2,092 ⟶ 2,410:
show_message("'" + first + "' does not end with '" + second + "'");
}
}</
{{out}} (in message boxes, 1 per line):
Line 2,101 ⟶ 2,419:
=={{header|Go}}==
<
import (
Line 2,130 ⟶ 2,448:
func main() {
match("abracadabra", "abr")
}</
{{out}}
<pre>
Line 2,143 ⟶ 2,461:
=={{header|Groovy}}==
Examples:
<
assert ! "abcd".startsWith("zn")
assert "abcd".endsWith("cd")
Line 2,165 ⟶ 2,483:
assert indicesOf("abab", "ab") == [0, 2]
assert indicesOf("abab", "ba") == [1]
assert indicesOf("abab", "xy") == []</
All assertions pass, so there is no output.
=={{header|Haskell}}==
<
> "abc" `isPrefixOf` "abcdefg"
True
Line 2,181 ⟶ 2,499:
> let infixes a b = findIndices (isPrefixOf a) $ tails b
> infixes "ab" "abcdefabqqab"
[0,6,10]</
=={{header|Icon}} and {{header|Unicon}}==
<
write("Matching s2 :=",image(s2 := "ab")," within s1:= ",image(s1 := "abcdabab"))
Line 2,193 ⟶ 2,511:
write("Test #3 ending ", if s1[0-:*s2] == s2 then "matches" else "fails")
end</
{{out}}
Line 2,202 ⟶ 2,520:
=={{header|J}}==
<
contains=: +./@:E.~
endswith=: ] -: ({.~ -@#)</
Example use:
<
1
'abcd' startswith 'cd'
Line 2,225 ⟶ 2,543:
1
'abab' I.@E.~ 'ab' NB. find starting indicies
0 2</
Note that these verbs contain no constraints restricting them to sequences of characters and so also apply to arrays of type other than character:
<
1
4.2 5.1 1.3 9 3 contains 1.3 4.2 NB. floating point
0
4.2 5.1 1.3 4.2 9 3 contains 1.3 4.2
1</
=={{header|Java}}==
For this task consider the following strings
<syntaxhighlight lang="java">
String string = "string matching";
String suffix = "ing";
</syntaxhighlight>
The most idiomatic way of determining if a string starts with another string is to use the ''String.startsWith'' method.
<syntaxhighlight lang="java">
string.startsWith(suffix)
</syntaxhighlight>
Another way is to use a combination of ''String.substring'' and ''String.equals''
<syntaxhighlight lang="java">
string.substring(0, suffix.length()).equals(suffix)
</syntaxhighlight>
To determine if a string contains at least one occurrence of another string, use the ''String.contains'' method.
<syntaxhighlight lang="java">
string.contains(suffix)
</syntaxhighlight>
A slightly more idiomatic approach would be to use the ''String.indexOf'' method, which will also return the index of the first character.
<syntaxhighlight lang="java">
string.indexOf(suffix) != -1
</syntaxhighlight>
The most idiomatic way of determining whether a string ends with another string is to use the ''String.endsWith'' method.
<syntaxhighlight lang="java">
string.endsWith(suffix);
</syntaxhighlight>
Similarly, a combination of ''String.substring'' and ''String.equals'' can be used.
<syntaxhighlight lang="java">
string.substring(string.length() - suffix.length()).equals(suffix)
</syntaxhighlight>
If you're looking to find the index of each occurrence, you can use the following.
<syntaxhighlight lang="java">
int indexOf;
int offset = 0;
while ((indexOf = string.indexOf(suffix, offset)) != -1) {
System.out.printf("'%s' @ %d to %d%n", suffix, indexOf, indexOf + suffix.length() - 1);
offset = indexOf + 1;
}
</syntaxhighlight>
<pre>
'ing' @ 3 to 5
'ing' @ 12 to 14
</pre>
<br />
Alternately
<syntaxhighlight lang="java">"abcd".startsWith("ab") //returns true
"abcd".endsWith("zn") //returns false
"abab".contains("bb") //returns false
Line 2,242 ⟶ 2,604:
int loc = "abab".indexOf("bb") //returns -1
loc = "abab".indexOf("ab") //returns 0
loc = "abab".indexOf("ab",loc+1) //returns 2
</syntaxhighlight>
<syntaxhighlight lang="java">
public class JavaApplication6 {
public static void main(String[] args) {
String strOne = "complexity";
String strTwo = "udacity";
stringMatch(strOne, strTwo);
}
Line 2,281 ⟶ 2,639:
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
<
, stringB = "co"
, q1, q2, q2multi, m
Line 2,310 ⟶ 2,669:
console.log(" In fact, it happens "+q2matches.length+" times within '"+stringA+"', at index"+(q2matches.length > 1 ? "es" : "")+" "+q2matches.join(', ')+".")
}
console.log("3: Does '"+stringA+"' end with '"+stringB+"'? " + ( q3 ? "Yes." : "No."))</
{{out}}
Line 2,320 ⟶ 2,679:
=={{header|jq}}==
Using the builtins of jq 1.4 and later:
<
"abc" | startswith("ab")
#=> true</
<
# so the jq test "if index(_) then ...." can be used
# without any type conversion.
"abcd" | index( "bc")
#=> 1</
<
"abc" | endswith("bc")
#=> true</
Using the regex functions available in jq 1.5:
<
"abcd" | test("bc")
"abcd" | test("cd$")</
===Multiple Occurrences===
To determine all the indices of one string in another:
<
jq -n '"abcdabcd" | indices("bc")'
[
1,
5
]</
In jq 1.5, the regex function match/1 can also be used:
<
1
5</
=={{header|Julia}}==
<
startswith("abcd","ab") #returns true
findfirst("ab", "abcd") #returns 1:2, indices range where string was found
Line 2,365 ⟶ 2,724:
println(r.offset)
end #returns 1, then 3 matching the two starting indices where the substring was found
</syntaxhighlight>
=={{header|K}}==
<
endswith: {0=(-#y)+(#x)-*_ss[x;y]}
contains: {0<#_ss[x;y]}</
'''Example:'''
<
1
startswith["abcd";"bc"]
Line 2,387 ⟶ 2,746:
0
_ss["abcdabceabc";"abc"] / location of matches
0 4 8</
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
fun main() {
val s1 = "abracadabra"
val s2 = "abra"
println("$s1 begins with $s2
println("$s1 ends with $s2
val b
if (b) {
print("$s1 contains $s2 at these indices: ")
// can use indexOf to get first index or lastIndexOf to get last index
// to get ALL indices, use a for loop or Regex
println(
s2.toRegex(RegexOption.LITERAL).findAll(s1).joinToString { it.range.start.toString() }
)
}
else println("$s1 does not contain $2.")
}</syntaxhighlight>
{{out}}
<pre>
abracadabra begins with abra
abracadabra ends with abra
abracadabra contains abra at these
</pre>
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
exec 2> /tmp/String_matching.err
# String matching
# # 1. Determine if the first string starts with second string.
# # 2. Determine if the first string contains the second string at any location
# # 3. Determine if the first string ends with the second string
# # 4. Print the location of the match for part 2
# # 5. Handle multiple occurrences of a string for part 2
# # Variables:
#
typeset -a bounds=( [0]="no Match" [1]="Starts with" [255]="Ends with" )
typeset -a string=( "Hello" "hello world" "William Williams" "Yabba dabba do" )
typeset -a substr=( "Hell" "Do" "abba" "Will" "orld" )
# # Functions:
#
# # Function _bounds(str, substr) - return 1 for starts with 255 for endswith
#
function _bounds {
typeset _str ; _str="$1"
typeset _sub ; _sub="$2"
typeset _FALSE _STARTS _ENDS ; integer _FALSE=0 _STARTS=1 _ENDS=255
[[ "${_str}" == "${_sub}"* ]] && return ${_STARTS}
[[ "${_str}" == *"${_sub}" ]] && return ${_ENDS}
return ${_FALSE}
}
# # Function _contains(str, substr) - return 0 no match arr[pos1 ... posn]
#
function _contains {
typeset _str ; _str="$1"
typeset _sub ; _sub="$2"
typeset _arr ; nameref _arr="$3"
typeset _FALSE _TRUE _i _match _buff ; integer _FALSE=0 _TRUE=1 _i _match
[[ "${_str}" != *"${_sub}"* ]] && return ${_FALSE}
for ((_i=0; _i<=${#_str}-${#_sub}; _i++)); do
_buff=${_str:${_i}:$((${#_str}-_i))}
[[ ${_buff} != ${_buff#${_sub}} ]] && _arr+=( $(( _i+1 )) )
done
return ${_TRUE}
}
######
# main #
######
integer i j rc
typeset -a posarr
for ((i=0; i<${#string[*]}; i++)); do
for ((j=0; j<${#substr[*]}; j++)); do
_bounds "${string[i]}" "${substr[j]}" ; rc=$?
print "${string[i]} ${bounds[rc]} ${substr[j]}"
_contains "${string[i]}" "${substr[j]}" posarr ; rc=$?
((! rc)) && print "${string[i]} ${substr[j]} ${bounds[rc]}es" && continue
print "${string[i]} + ${substr[j]} ${#posarr[*]} matches at ${posarr[*]}"
unset posarr ; typeset -a posarr
done
done</syntaxhighlight>
{{out}}<pre>
Hello Starts with Hell
Hello + Hell 1 matches at 1
Hello no Match Do
Hello Do no Matches
Hello no Match abba
Hello abba no Matches
Hello no Match Will
Hello Will no Matches
Hello no Match orld
Hello orld no Matches
hello world no Match Hell
hello world Hell no Matches
hello world no Match Do
hello world Do no Matches
hello world no Match abba
hello world abba no Matches
hello world no Match Will
hello world Will no Matches
hello world Ends with orld
hello world + orld 1 matches at 8
William Williams no Match Hell
William Williams Hell no Matches
William Williams no Match Do
William Williams Do no Matches
William Williams no Match abba
William Williams abba no Matches
William Williams Starts with Will
William Williams + Will 2 matches at 1 9
William Williams no Match orld
William Williams orld no Matches
Yabba dabba do no Match Hell
Yabba dabba do Hell no Matches
Yabba dabba do no Match Do
Yabba dabba do Do no Matches
Yabba dabba do no Match abba
Yabba dabba do + abba 2 matches at 2 8
Yabba dabba do no Match Will
Yabba dabba do Will no Matches
Yabba dabba do no Match orld
Yabba dabba do orld no Matches</pre>
=={{header|LabVIEW}}==
Line 2,415 ⟶ 2,892:
[[File:LabVIEW_Character_matching_2.png]]<br/>
[[File:LabVIEW_Character_matching_3.png]]
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def S.in
{def S.in.r {lambda {:c :w :i :n}
{if {= :i :n}
then -1
else {if {W.equal? :c {W.get :i :w}}
then :i
else {S.in.r :c :w {+ :i 1} :n}}}}}
{lambda {:c :w}
{S.in.r :c :w 0 {W.length :w}}}}
-> S.in
{def startswith
{lambda {:w1 :w2}
{= {S.in _ {S.replace :w2 by _ in :w1}} 0}}}
-> startswith
{def endswith
{lambda {:w1 :w2}
{= {S.in _ {S.replace :w2 by _ in :w1}}
{- {W.length :w1} {W.length :w2}}}}}
-> endswith
{def isin
{lambda {:w1 :w2}
{S.in _ {S.replace :w2 by _ in :w1}}}}
-> isin
{startswith nabuchodonosor nabu}
-> true
{startswith nabuchodonosor abu}
-> false
{endswith nabuchodonosor sor}
-> true
{endswith nabuchodonosor oso}
-> false
{isin nabuchodonosor oso}
-> 10 // is in at 10
{isin nabuchodonosor xyz}
-> -1 // is not in
</syntaxhighlight>
=={{header|Lang5}}==
<
: comb "" split ; : concat "" join ; : dip swap '_ set execute _ ;
: first 0 extract swap drop ; : flip comb reverse concat ;
Line 2,436 ⟶ 2,961:
"rosettacode" "ocat" contains . # 0
"rosettacode" "edoc" end-with . # 0
"rosettacode" "code" contains . # 7</
=={{header|Lasso}}==
<
a = 'a quick brown peanut jumped over a quick brown fox',
b = 'a quick brown'
Line 2,453 ⟶ 2,978:
//Determining if the first string ends with the second string
#a->endswith(#b) // false</
=={{header|Liberty BASIC}}==
<
st1$="first string"
st2$="first"
Line 2,486 ⟶ 3,011:
print "First string ends with second string."
end if
</syntaxhighlight>
=={{header|Lingo}}==
<
b = "Hello"
Line 2,510 ⟶ 3,035:
-- Print the location of the match for part 2
put offset(b, a)
-- 7</
=={{header|Logo}}==
<
if empty? :sub [output "true]
if empty? :thing [output "false]
Line 2,529 ⟶ 3,054:
show starts.with? "dog "doghouse ; true
show ends.with? "house "doghouse ; true
show substring? "gho "doghouse ; true (built-in)</
=={{header|Lua}}==
<
s2 = "str"
s3 = "ing"
Line 2,544 ⟶ 3,069:
print( "s1 ends with s2: ", select( 2, string.find( s1, s2 ) ) == string.len( s1 ) )
print( "s1 ends with s3: ", select( 2, string.find( s1, s3 ) ) == string.len( s1 ) )</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module StringMatch {
A$="Hello World"
Line 2,562 ⟶ 3,087:
Print A$ ~ "*orld"
}
StringMatch
</syntaxhighlight>
{{out}}
<pre>
Line 2,571 ⟶ 3,098:
True
</pre>
=={{header|Maple}}==
These facilities are all to be found in the StringTools package in Maple.
<syntaxhighlight lang="maple">
> with( StringTools ): # bind package exports at the top-level
> s := "dzrIemaWWIMidXYZwGiqkOOn":
Line 2,608 ⟶ 3,133:
> {seq}( s[ i .. i + 2 ], i = p ); # check them
{"XYZ"}
</syntaxhighlight>
The StringTools package also contains facilities for regular expression matching, but for fixed string patterns, the Search and SearchAll tools are much faster.
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
EndWith[x_, y_] := MemberQ[Flatten[StringPosition[x, y]], StringLength[x]]
StartWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"]
EndWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"]
StringPosition["XYZaaabXYZaaaaXYZXYZ", "XYZ"]</
{{out}}
<pre>True
Line 2,623 ⟶ 3,148:
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
% 1. Determining if the first string starts with second string
strcmp(str1,str2,length(str2))
Line 2,635 ⟶ 3,160:
% 2. Handle multiple occurrences of a string for part 2.
ix = strfind(s1,s2); % ix is a vector containing the starting positions of s2 within s1
</syntaxhighlight>
=={{header|min}}==
One way might be:
{{works with|min|0.19.6}}
<
(indexof -1 !=) :contains?
((/ $/) swap 1 insert "" join regex ("") !=) :ends-with?
Line 2,646 ⟶ 3,171:
"minimalistic" "min" starts-with? puts!
"minimalistic" "list" contains? puts!
"minimalistic" "list" ends-with? puts!</
{{out}}
<pre>
Line 2,657 ⟶ 3,182:
We first extend the built-in string class with three new methods, and then demonstrate their use on some sample strings.
<
return self.len >= s.len and s[:s.len] == s
end function
Line 2,696 ⟶ 3,221:
print
print firstQ + doesOrNot[first.endsWith(second)] + "end with " + secondQ</
{{out}}
<pre>
Line 2,707 ⟶ 3,232:
"The brown dog jumped jumped and jumped" does end with "jumped"
</pre>
=={{header|MIPS Assembly}}==
The function below returns the zero-based index where the string pointed to by <code>$a1</code> occurs in <code>$a0</code>.
* If it returns <tt>strlen($a0)</tt>, then <tt>$a1</tt> was not found.
* If it returns 0, then <tt>$a0</tt> begins with <tt>$a1</tt>.
* If it returns <tt>strlen($a0)-strlen($a1)</tt>, then <tt>$a0</tt> ends with <tt>$a1</tt>.
* Otherwise, <tt>$a0</tt> contains <tt>$a1</tt> starting at the specified location.
* Multiple occurrences can be detected by adding the output to <tt>$a0</tt> and repeating the process; this is left as an exercise to the reader.
<syntaxhighlight lang="mips">InString:
;input: $a0 = ptr to string 1
; $a1 = ptr to string 2
; assumes len($a1) <= len($a0)
;out: $v0 = zero-based index where the second string is placed in the first.
;clobbers: $t0,$t1
subiu sp,sp,4 ;set up a stack frame of 4 bytes.
sw $a1,(sp)
li $v0,0
InString_again:
lbu $t0,($a0)
nop
beqz $t0,InString_terminated
nop
lbu $t1,($a1)
nop
beqz $t1,InString_terminated
nop
bne $t0,$t1,InString_noMatch
nop
b InString_overhead
addiu $a1,1
InString_noMatch:
lw $a1,(sp) ;reset the substring pointer if the letters don't match
addiu $v0,1 ;load delay slot
InString_overhead:
addiu $a0,1
b InString_Again
nop
InString_terminated:
addiu sp,sp,4
jr ra
nop</syntaxhighlight>
{{out}}
<syntaxhighlight lang="mips">main:
la $a0,MyString
la $a1,Test1 ;this code was recompiled 5 times, testing a different string each time.
jal InString
nop
jal Monitor
nop
shutdown:
nop ;Project 64 will detect an infinite loop and close the ROM if I don't have this nop here.
b shutdown
nop
MyString: ;this was loaded into $a0
.ascii "abcdefghijklmnopqrstuvwxyz"
.byte 0
.align 4
;each of these was loaded into $a1 individually for testing
Test1:
.ascii "abc" ;InString returned 0
.byte 0
.align 4
Test2:
.ascii "xyz" ;InString returned 0x17 (decimal 23)
.byte 0
.align 4
Test3:
.ascii "def" ;InString returned 3
.byte 0
.align 4
Test4:
.ascii "z",0 ;InString returned 0x19 (decimal 25)
.byte 0
.align 4
Test5:
.ascii "1",0 ;InString returned 0x1A (decimal 26)
.byte 0
.align 4</syntaxhighlight>
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols
Line 2,757 ⟶ 3,370:
return
</syntaxhighlight>
----
=={{header|NewLISP}}==
<
;; test if str starts with "ab"
Line 2,779 ⟶ 3,392:
(push idx pos -1))))
(find-all-pos "bc" str)</
=={{header|Nim}}==
<
let s = "The quick brown fox"
if s.startsWith("The quick"):
echo "Starts with “The quick”."
if s.endsWith("brown Fox"):
echo "Ends with “brown fox”."
if s.contains(" brown "):
echo "Contains “ brown ”."
if "quick" in s:
echo "Contains “quick”." # Alternate form for "contains".
let pos = find(s, " brown ") # -1 if not found.
if pos >= 0:
echo "“ brown ” is located at position: " & $pos</syntaxhighlight>
{{out}}
<pre>Starts with
Contains “quick”.
“ brown ” is located at position: 9</pre>
=={{header|Objeck}}==
<
bundle Default {
class Matching {
Line 2,812 ⟶ 3,432:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<
[@"abcd" hasSuffix:@"zn"] //returns false
int loc = [@"abab" rangeOfString:@"bb"].location //returns -1
loc = [@"abab" rangeOfString:@"ab"].location //returns 0
loc = [@"abab" rangeOfString:@"ab" options:0 range:NSMakeRange(loc+1, [@"abab" length]-(loc+1))].location //returns 2</
=={{header|OCaml}}==
<
let len1 = String.length s1
and len2 = String.length s2 in
if len1 < len2 then false else
let sub = String.sub s1 0 len2 in
(sub = s2)</
testing in the top-level:
Line 2,837 ⟶ 3,457:
- : bool = true
<
let len1 = String.length s1
and len2 = String.length s2 in
Line 2,846 ⟶ 3,466:
if (sub = s2) then true else aux (pred i)
in
aux (len1 - len2)</
# match2 "It's raining, Hello World!" "umbrella" ;;
Line 2,853 ⟶ 3,473:
- : bool = true
<
let len1 = String.length s1
and len2 = String.length s2 in
if len1 < len2 then false else
let sub = String.sub s1 (len1 - len2) len2 in
(sub = s2)</
# match3 "Hello World" "Hello" ;;
Line 2,865 ⟶ 3,485:
- : bool = true
<
let len1 = String.length s1
and len2 = String.length s2 in
Line 2,874 ⟶ 3,494:
if (sub = s2) then (true, i) else aux (pred i)
in
aux (len1 - len2)</
# match2_loc "The sun's shining, Hello World!" "raining" ;;
Line 2,881 ⟶ 3,501:
- : bool * int = (true, 10)
<
let len1 = String.length s1
and len2 = String.length s2 in
Line 2,892 ⟶ 3,512:
else aux (pred i) (n)
in
aux (len1 - len2) 0</
# match2_num "This cloud looks like a camel, \
Line 2,900 ⟶ 3,520:
that other cloud looks like a llama" "cloud" ;;
- : bool * int = (true, 2)
=={{header|Odin}}==
<syntaxhighlight lang="odin">package main
import "core:fmt"
import "core:strings"
main :: proc() {
using strings
s := "Hello world"
fmt.println(has_prefix(s, "He"), contains(s, "wo"), has_suffix(s, "ld"))
// Output: true true true
fmt.println(index(s, "wo"))
// Output: 6
}</syntaxhighlight>
=={{header|Oforth}}==
<
| i |
s2 isAllAt(s1, 1) ifTrue: [ System.Out s1 << " begins with " << s2 << cr ]
Line 2,916 ⟶ 3,555:
System.Out s1 << " includes " << s2 << " at position : " << i << cr
i s2 size + ->i
] ;</
{{out}}
Line 2,932 ⟶ 3,571:
=={{header|OxygenBasic}}==
<
string s="sdfkjhgsdfkdfgkbopefioqwurti487sdfkrglkjfs9wrtgjglsdfkdkjcnmmb.,msfjflkjsdfk"
Line 2,968 ⟶ 3,607:
'
'Total matches: 5
</syntaxhighlight>
=={{header|PARI/GP}}==
This meets the first but not the second of the optional requirements. Note that GP treats any nonzero value as true so the location found by contains() can be ignore if not needed.
<
string=Vec(string);
prefix=Vec(prefix);
Line 2,998 ⟶ 3,637:
for(i=1,#suffix,if(prefix[i]!=string[i+#string-#suffix], return(0)));
1
};</
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
##
Println('abcd'.StartsWith('ab'));
Println('abcd'.EndsWith('cd'));
var abra := 'abracadabra';
Println('bra' in abra);
var ind := abra.IndexOf('bra');
var ind1 := abra.IndexOf('bra', ind + 1);
Println(ind,ind1);
abra.Matches('bra').Select(m -> m.Index).Println
</syntaxhighlight>
{{out}}
<pre>
True
True
True
1 8
1 8
</pre>
=={{header|Perl}}==
Line 3,004 ⟶ 3,665:
Using regexes:
<
$str1 =~ /\Q$str2\E/ # true if $str1 contains $str2
$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2</
Using <code>index</code>:
<
index($str1, $str2) != -1 # true if $str1 contains $str2
rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2</
Using <code>substr</code>:
<
substr($str1, - length($str2)) eq $str2 # true if $str1 ends with $str2</
Bonus task ''(printing all positions where <code>$str2</code> appears in <code>$str1</code>)'':
<
<
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"the"</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- (also try this with "th"/"he")</span>
<span style="color: #000000;">sentence</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"the last thing the man said was the"</span>
<span style="color: #000080;font-style:italic;">-- sentence = "thelastthingthemansaidwasthe" -- (practically the same results)
-- A common, but potentially inefficient idiom for checking for a substring at the start is:</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"yes(1)"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000080;font-style:italic;">-- A more efficient method is to test the appropriate slice</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)>=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)]=</span><span style="color: #000000;">word</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"yes(2)"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000080;font-style:italic;">-- Which is almost identical to checking for a word at the end</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)>=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">sentence</span><span style="color: #0000FF;">[-</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">word</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"yes(3)"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000080;font-style:italic;">-- Or sometimes you will see this, a tiny bit more efficient:</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)>=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">and</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)-</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"yes(4)"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000080;font-style:italic;">-- Finding all occurences is a snap:</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">r</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000080;font-style:italic;">-- or equivalently:</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">match_all</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,063 ⟶ 3,729:
16
33
{1,16,33}
</pre>
=={{header|Phixmonti}}==
Simple solution
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/String_prepend
by Galileo, 11/2022 #/
include ..\Utilitys.pmt
"the last thing the man said was the" "the" pstack
len var l >ps
1 l slice tps == if "Begins with keyword" ? endif
0 l - l slice tps == if "Ends with keyword" ? endif
tail ps> find dup if "Keyword appears first at " print 1 + print " position" ? else drop endif
drop
</syntaxhighlight>
{{out}}
<pre>
["the last thing the man said was the", "the"]
Begins with keyword
Ends with keyword
Keyword appears first at 16 position
=== Press any key to exit ===</pre>
More complex solution
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/String_prepend
by Galileo, 11/2022 #/
include ..\Utilitys.pmt
"the last thing the man said was the" "the" pstack
( ) rot rot >ps
true while
tps find dup >ps
if swap tps 0 put swap 32 ps> set true else ps> endif
endwhile
len ps> len nip - 1 + >ps drop
len for get
dup 1 == if "Begins with keyword" ? drop else
dup tps == if "Ends with keyword" ? drop else
"Locate at position " print ?
endif endif
endfor
ps> drop
</syntaxhighlight>
{{out}}
<pre>
["the last thing the man said was the", "the"]
Begins with keyword
Locate at position 16
Ends with keyword
=== Press any key to exit ===</pre>
=={{header|PHP}}==
<
/**********************************************************************************
* This program gets needle and haystack from the caller (chm.html) (see below)
Line 3,124 ⟶ 3,846:
<p style="color: red";><strong><?php echo "$tx1" ?></strong></p>
</body>
</html></
<
<!DOCTYPE html>
<!--
Line 3,165 ⟶ 3,887:
</form>
</body>
</html></
=={{header|Picat}}==
The two most common predicate to use for string matching is <code>find/4</code> (find a substring) or <code>append/3</code> (a general purpose reversible predicate for concatenating/splitting lists/strings). Both predicates are non-deterministic and can yield multiple solutions, e.g. together with <code>findall/2</code>.
<syntaxhighlight lang="picat">import util.
go =>
S1 = "string second",
S2 = "string",
% - Determining if the first string starts with second string
println("Using find/4"),
if find(S1,S2,1,_) then
println("S1 starts with S2")
else
println("S1 does not start with S2")
end,
println("Using append/3"),
if append(S2,_,S1) then
println("S1 starts with S2")
else
println("S1 does not start with S2")
end,
% - Determining if the first string contains the second string at any location
S3 = "this is a string",
S4 = "is a",
if find(S3,S4,Start4,End4) then
printf("S3 contains S4 at pos %d..%d\n", Start4,End4)
else
println("S3 does not contain S4")
end,
% - Determining if the first string ends with the second string
S5 = "this is a string",
S6 = "string",
if find(S5,S6,Start6,S5.length) then
printf("S5 ends with S6, startpos: %d\n",Start6)
else
println("S5 does not end with S6")
end,
if append(_,S6,S5) then
println("S5 ends with S6")
else
println("S5 does not end with S6")
end,
S7 = "this is a string or a string",
S8 = "a string",
All = findall([Start8,End8], find(S7,S8,Start8,End8)),
println(positions=All),
% searching for " "
All2 = findall([Start9,End9], find(S7," ",Start9,End9)),
println(positions=All2),
nl.</syntaxhighlight>
{{out}}
<pre>Using find/4
S1 starts with S2
Using append/3
S1 starts with S2
S3 contains S4 at pos 6..9
S5 ends with S6, startpos: 11
S5 ends with S6
positions = [[9,16],[21,28]]
positions = [[5,5],[8,8],[10,10],[17,17],[20,20],[22,22]]</pre>
=={{header|PicoLisp}}==
<
-> "abcd"
: (pre? "xy" "abcd")
Line 3,191 ⟶ 3,982:
: (positions "bc" "abcdabcd")
-> (2 6)</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* Let s be one string, t be the other that might exist within s. */
/* 8-1-2011 */
Line 3,206 ⟶ 3,997:
if k > 0 then put skip edit (t, ' starts at position ', k) (a);
</syntaxhighlight>
Optional extra:
<syntaxhighlight lang="pl/i">
/* Handle multiple occurrences. */
n = 1;
Line 3,231 ⟶ 4,022:
else stop;
end;
</syntaxhighlight>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
"spicywiener".StartsWith("spicy")
"spicywiener".Contains("icy")
Line 3,240 ⟶ 4,031:
"spicywiener".IndexOf("icy")
[regex]::Matches("spicywiener", "i").count
</syntaxhighlight>
{{out}}
<pre>
Line 3,253 ⟶ 4,044:
<
:- system:set_prolog_flag(double_quotes,codes) .
Line 3,297 ⟶ 4,088:
.
</syntaxhighlight>
{{out}}
Line 3,366 ⟶ 4,157:
=={{header|PureBasic}}==
<
Protected Result
If FindString(String1$, String2$, 1) =1 ; E.g Found in possition 1
Line 3,380 ⟶ 4,171:
EndIf
ProcedureReturn Result
EndProcedure</
And a verification
<
PrintN(Str(StartsWith("Rosettacode", "Rosetta"))) ; = 1
PrintN(Str(StartsWith("Rosettacode", "code"))) ; = 0
Line 3,392 ⟶ 4,183:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
An alternate and more complete solution:
<
;returns one if string1$ starts with string2$, otherwise returns zero
If FindString(string1$, string2$, 1) = 1
Line 3,436 ⟶ 4,227:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre>1
Line 3,451 ⟶ 4,242:
=={{header|Python}}==
<
"abcd".endswith("zn") #returns False
"bb" in "abab" #returns False
Line 3,457 ⟶ 4,248:
loc = "abab".find("bb") #returns -1
loc = "abab".find("ab") #returns 0
loc = "abab".find("ab",loc+1) #returns 2</
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
DefStr S
DefInt P
string2 = "dogs"
string1 = "dogs and cats are often enemies,because dogs are stronger than cats, but cats sometimes can be friend to dogs"
position = 0
pcount = 0
Print "Searching "; string2; " into "; string1
While (InStr(position, string1, string2) > 0)
position = InStr(position + 1, string1, string2)
pcount = pcount + 1
If position = 1 Then Print string1; "- starts with -"; string2
Print position
If position = Len(string1) - Len(string2) + 1 Then
Print string1; "- ends with -"; string2
Exit While
End If
Wend
Print string2; " is present "; pcount; " times into "; string1
</syntaxhighlight>
=={{header|Quackery}}==
These work for any nests (i.e. dynamic arrays), not just strings (i.e. nests of chars).
<syntaxhighlight lang="quackery"> [ tuck size split drop = ] is starts ( [ [ --> b )
[ tuck size negate split nip = ] is ends ( [ [ --> b )
[ 2dup = iff true
else
[ over [] = iff false done
2dup starts iff true done
dip behead nip again ]
dip 2drop ] is contains ( [ [ --> b )
[ iff
[ say "true" ]
else
[ say "false" ] ] is echobool ( b --> )
$ "abcdefgh" $ "abc" starts echobool cr
$ "abcdefgh" $ "xyz" starts echobool cr
$ "abcdefgh" $ "fgh" ends echobool cr
$ "abcdefgh" $ "xyz" ends echobool cr
$ "abcdefgh" $ "cde" contains echobool cr
$ "abcdefgh" $ "xyz" contains echobool cr</syntaxhighlight>
{{out}}
<pre>true
false
true
false
true
false
</pre>
=={{header|Racket}}==
<
#lang racket
(require srfi/13)
Line 3,467 ⟶ 4,317:
(string-contains "abab" "bb")
(string-contains "abab" "ba")
</syntaxhighlight>
{{out}}
<pre>
Line 3,481 ⟶ 4,331:
Using string methods:
<syntaxhighlight lang="raku"
$haystack.contains($needle) # True if $haystack contains $needle
$haystack.ends-with($needle) # True if $haystack ends with $needle</
Using regexes:
<syntaxhighlight lang="raku"
so $haystack ~~ / $needle / # True if $haystack contains $needle
so $haystack ~~ / $needle $/ # True if $haystack ends with $needle</
Using <code>substr</code>:
<syntaxhighlight lang="raku"
substr($haystack, *-$needle.chars) eq $needle # True if $haystack ends with $needle</
Bonus task:
<syntaxhighlight lang="raku"
$haystack.indices($needle :overlap); # Also find any overlapping instances of $needle in $haystack</
=={{header|Retro}}==
<
withLength &swap dip 0 swap ^strings'getSubset compare ;
Line 3,515 ⟶ 4,365:
"abcdefghijkl" "ijkl" endsWith?
"abcdefghijkl" "abc" endsWith?</
=={{header|REXX}}==
Extra coding was added to take care of using plurals in the last output message.
<
parse arg A B /*obtain A and B from the command line.*/
say 'string A = ' A /*display string A to the terminal.*/
Line 3,544 ⟶ 4,394:
if #==0 then say "string A doesn't contain string B"
else say 'string A contains string B ' # " time"left('s', #>1),
"(at position"left('s', #>1) $")" /*stick a fork in it, we're all done. */</
{{out|output|text= when the following is specified (the five Marx brothers): <tt> Chico_Harpo_Groucho_Zeppo_Gummo p </tt> }}
<pre>
Line 3,599 ⟶ 4,449:
=={{header|Ring}}==
<
aString = "Welcome to the Ring Programming Language"
bString = "Ring"
bStringIndex = substr(aString,bString)
if bStringIndex > 0 see "" + bStringIndex + " : " + bString ok
</syntaxhighlight>
=={{header|RPL}}==
===Determining if the first string starts with second string===
Returns 1 if the strings match accordingly, 0 otherwise.
"ABCDEF" "ABC"
≪ SWAP OVER SIZE 1 SWAP SUB == ≫ EVAL
===Determining if the first string contains the second string at any location===
Returns the position of the first character of the second string in the first string if the strings match accordingly, 0 otherwise.
"ABCDEF" "BCD"
POS
===Determining if the first string ends with the second string===
Returns 1 if the strings match accordingly, 0 otherwise.
"ABCDEF" "DEF"
≪ SWAP DUP2 SIZE SWAP SIZE - 1 + OVER SIZE SUB == ≫ EVAL
{{out}}
<pre>
3: 1
2: 2
1: 1
</pre>
=={{header|Ruby}}==
<
p 'abcd'.end_with?('ab') #returns false
p 'abab'.include?('bb') #returns false
Line 3,616 ⟶ 4,485:
p 'abab'.index('ab') #returns 0
p 'abab'.index('ab', 1) #returns 2
p 'abab'.rindex('ab') #returns 2</
=={{header|Run BASIC}}==
<
s2$ = "abc" ' begins with
s3$ = "ef" ' is in the string
Line 3,646 ⟶ 4,515:
if mid$(s1$,len(s1$) + 1 - len(sn4$),len(sn4$)) <> sn4$ then a$ = "Not "
print "String:";s1$;" does ";a$;"end with:";sn4$</
{{out}}
<pre>
Line 3,658 ⟶ 4,527:
=={{header|Rust}}==
<
match possible_match {
Some(match_pos) => println!("Found match at pos {}", match_pos),
Line 3,679 ⟶ 4,548:
// Determining if the first string ends with the second string
assert!(s2.ends_with(s3));
}</
<
fn main(){
let hello = String::from("Hello world");
Line 3,688 ⟶ 4,557:
hello.ends_with("ld"),
hello.contains("wi"));
}</
{{out}}
Line 3,696 ⟶ 4,565:
=={{header|Scala}}==
<
"abcd".endsWith("zn") //returns false
"abab".contains("bb") //returns false
Line 3,703 ⟶ 4,572:
var loc="abab".indexOf("bb") //returns -1
loc = "abab".indexOf("ab") //returns 0
loc = "abab".indexOf("ab", loc+1) //returns 2</
=={{header|sed}}==
The following programs handle the input lines pairwise: If the first string of a pair contains the second string, the former one is shown. (Which means that non-matching pairs are filtered out.)
1. Determining if the first string starts with the second string:
<syntaxhighlight lang="sed">N;/^\(.*\).*\n\1$/!d;s/\n.*//</syntaxhighlight>
2. Determining if the first string contains the second string at any location:
<syntaxhighlight lang="sed">N;/.*\(.*\).*\n\1$/!d;s/\n.*//</syntaxhighlight>
3. Determining if the first string ends with the second string:
<syntaxhighlight lang="sed">N;/\(.*\)\n\1$/!d;s/\n.*//</syntaxhighlight>
{{out}}
<pre>
$ printf '%s\n' abcd bcd wxyz wxy | sed -f match1.sed
wxyz
$ printf '%s\n' abcd be vwxyz wxy | sed -f match2.sed
vwxyz
$ printf '%s\n' abcd abc wxyz xyz | sed -f match3.sed
wxyz
</pre>
=={{header|Seed7}}==
<
const proc: main is func
Line 3,721 ⟶ 4,609:
position := pos("abab", "ab", succ(position));
writeln(position); # position is 3
end func;</
{{out}}
Line 3,735 ⟶ 4,623:
=={{header|Sidef}}==
<
var second = "abc";
Line 3,749 ⟶ 4,637:
while (pos = first.index(second, pos+1) != -1) {
say "Match at pos: #{pos}";
}</
=={{header|Smalltalk}}==
<
a includesSubCollection: b. "inherited from superclass"
a includesString: b. "the same, but more readable"
a endsWith: b
a indexOfSubCollection: b "inherited"
a indexOfSubCollection: b startingAt: pos
a indexOfString: b
a indexOfStringStartingAt: b
</syntaxhighlight>
=={{header|SNOBOL4}}==
<
s2 = 'ab'
s3 = 'xy'
Line 3,772 ⟶ 4,664:
p3 OUTPUT = ?(s1 ? s2 RPOS(0)) "3. " s2 " ends " s1
END</
{{out}}
<pre>1. ab begins abcdabefgab
Line 3,781 ⟶ 4,673:
=={{header|Standard ML}}==
<
String.isSuffix "zn" "abcd"; (* returns false *)
String.isSubstring "bb" "abab"; (* returns false *)
Line 3,787 ⟶ 4,679:
#2 (Substring.base (#2 (Substring.position "bb" (Substring.full "abab")))); (* returns 4 *)
val loc = #2 (Substring.base (#2 (Substring.position "ab" (Substring.full "abab")))); (* returns 0 *)
val loc' = #2 (Substring.base (#2 (Substring.position "ab" (Substring.extract ("abab", loc+1, NONE))))); (* returns 2 *)</
=={{header|Swift}}==
<
str.hasPrefix("Hell") //True
str.hasPrefix("hell") //False
Line 3,798 ⟶ 4,690:
str.hasSuffix("playground") //True
str.hasSuffix("world") //False</
=={{header|Tailspin}}==
This assumes the string to be found does not contain any regex special characters, otherwise we should work with composers (parsers) see below.
<
templates find&{s:}
when <'$s;.*'> do '$; starts with $s;' !
Line 3,820 ⟶ 4,712:
' -> !OUT::write
'abcd' -> find&{s:'e'} -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,830 ⟶ 4,722:
Working with composers and literal matchers to be able to handle any string.
<
composer startsWith&{s:}
@: 0;
Line 3,867 ⟶ 4,759:
' -> !OUT::write
'banana' -> find&{s:'na'} -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,879 ⟶ 4,771:
In tailspin we don't manipulate strings by character indices but we can still work out the second part. String characters can be streamed and captured in an array, although we prefer to compare in strings, here with a composer (parser).
This has also been crafted to work with strings containing special regex characters by using literal equality.
<
composer index&{s:}
@index: 0;
Line 3,893 ⟶ 4,785:
' -> !OUT::write
'c is found in positions $:'banana' -> index&{s:'c'}; in banana' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,903 ⟶ 4,795:
=={{header|Tcl}}==
In this code, we are looking in various ways for the string in the variable <tt>needle</tt> in the string in the variable <tt>haystack</tt>.
<
set isContained [expr {[string first $needle $haystack] >= 0}]
set isSuffix [string equal $needle [string range $haystack end-[expr {[string length $needle]-1}] end]]</
Of course, in the cases where the needle is a glob-safe string (i.e., doesn't have any of the characters “<tt>*?[\</tt>” in), this can be written far more conveniently:
<
set isContained [string match *$needle* $haystack]
set isSuffix [string match *$needle $haystack]</
Another powerful technique is to use the regular expression engine in literal string mode:
<
This can be extended by getting the <code>regexp</code> to return the locations of the matches, enabling the other forms of match to be done:
<
# Each match location is a pair, being the index into the string where the needle started
# to match and the index where the needle finished matching
Line 3,926 ⟶ 4,818:
foreach location $matchLocations {
puts "needle matched at index [lindex $location 0]"
}</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
ASK "string1", string1=""
Line 3,953 ⟶ 4,845:
PRINT string1," not ends with ",string2
ENDIF
</syntaxhighlight>
{{out}}
<pre>string1 >Rosetta Code
Line 3,968 ⟶ 4,860:
===TXR Lisp===
<
((big small)
(cond
Line 3,983 ⟶ 4,875:
(put-line `@small does not occur in @big`)))))
(otherwise
(put-line `usage: @(ldiff *full-args* *args*) <bigstring> <smallstring>`)))</
{{out}}
<pre>$ txr cmatch2.tl x
Line 4,004 ⟶ 4,896:
===Pattern Language===
<
@(cases)
@ line
Line 4,029 ⟶ 4,921:
first line is not found in the second line
@ (end)
@(end)</
{{out}}
Line 4,040 ⟶ 4,932:
0123
first line is a suffix of the second line</pre>
=={{header|Uiua}}==
{{works with|Uiua|0.11.1}}
Does <code>football</code> start with <code>foot</code>?
<syntaxhighlight lang="uiua">
⊢⦷"foot" "football" # 1
</syntaxhighlight>
Does <code>football</code> contain <code>otba</code>?
<syntaxhighlight lang="uiua">
/↥⌕"otba" "football" # 1
</syntaxhighlight>
Does <code>football</code> end with <code>ball</code>?
<syntaxhighlight lang="uiua">
⊢⇌⦷"ball" "football" # 1
</syntaxhighlight>
Where is <code>iss</code> in <code>Mississippi</code>?
<syntaxhighlight lang="uiua">
⊚⌕"iss" "Mississippi" # [1 4]
</syntaxhighlight>
=={{header|Vala}}==
<
var text = "一二三四五六七八九十";
var starts = "一二";
Line 4,055 ⟶ 4,966:
stdout.printf(@"contains $contains: $(contains in text)\n");
stdout.printf(@"contains $not_contain: $(contains in text)\n");
}</
{{out}}
Line 4,070 ⟶ 4,981:
=={{header|VBA}}==
{{trans|Phix}}<
word = "the" '-- (also try this with "th"/"he")
sentence = "the last thing the man said was the"
Line 4,100 ⟶ 5,011:
r = InStr(r + 1, sentence, word)
Loop
End Sub</
<pre>yes(1)
yes(2)
Line 4,110 ⟶ 5,021:
=={{header|VBScript}}==
<
StartsWith = False
If Left(s1,Len(s2)) = s2 Then
Line 4,152 ⟶ 5,063:
WScript.StdOut.Write "Contains test, 'o' in 'fooooobar': " & Contains("fooooobar","o")
WScript.StdOut.WriteLine
WScript.StdOut.Write "Ends with test, 'bar' in 'foobar': " & EndsWith("foobar","bar")</
{{out}}
Line 4,165 ⟶ 5,076:
{{works with|Visual Basic|VB6 Standard}}
works the same as in VBA, see [[String_matching#VBA]]
=={{header|V (Vlang)}}==
{{trans|Delphi}}
<syntaxhighlight lang="v (vlang)">fn main() {
str := 'abcd'
println(str.starts_with('ab')) // True
println(str.ends_with('zn')) // False
println(str.contains('bb')) // False
println(str.contains('ab')) // True
println(str.index('bc') or {-1}) // 1 // Vlang arrays are 0 based, so first char position is 0 and no result assigned -1
}</syntaxhighlight>
{{out}}
<pre>
true
false
false
true
1
</pre>
=={{header|Wren}}==
<
var t = "abra"
var u = "ra"
Line 4,184 ⟶ 5,115:
var contained = indices.count > 0
System.print("'%(s)' contains '%(u)' is %(contained) %(contained ? "at indices %(indices)" : "")")
System.print("'%(s)' ends with '%(v)' is %(s.endsWith(v))")</
{{out}}
Line 4,194 ⟶ 5,125:
=={{header|XPL0}}==
<
string 0; \use zero-terminated strings
Line 4,235 ⟶ 5,166:
Text(0, if StrFind(Str, "with") = StrLen(Str)-StrLen("with") then "yes" else "no"); CrLf(0); \3.
Text(0, if StrFind(Str, "x w" ) = StrLen(Str)-StrLen("x w" ) then "yes" else "no"); CrLf(0);
]</
{{out}}
Line 4,249 ⟶ 5,180:
=={{header|XProfan}}==
<syntaxhighlight lang="xprofan">
// XProfan can use StringParts, so the results here
// are the comma separated positions of the parts or 0
Line 4,299 ⟶ 5,230:
waitkey
end</
{{out}}
<pre>
Line 4,312 ⟶ 5,243:
(bar in foobar) Yes
</pre>
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
cadena1$ = "qwertyuiop"
//Determinar si la primera cadena comienza con la segunda cadena
cadena2$ = "qwerty"
if left$(cadena1$, len(cadena2$)) = cadena2$ then
print "'", cadena1$, "' comienza con '", cadena2$, "'"
else
print "'", cadena1$, "' no comienza con '", cadena2$, "'"
end if
//Determinar si la primera cadena contiene la segunda cadena en cualquier
//ubicación imprima la ubicación de la coincidencia para la parte 2
cadena2$ = "wert"
posic = instr(cadena1$, cadena2$)
if posic then
print "'", cadena1$, "' contiene '", cadena2$, "' en la posicion ", posic
else
print "'", cadena1$, "' no contiene '", cadena2$, "'"
end if
//Determinar si la primera cadena termina con la segunda cadena
cadena2$ = "random garbage"
if right$(cadena1$, len(cadena2$)) = cadena2$ then
print "'", cadena1$, "' termina con '", cadena2$, "'"
else
print "'", cadena1$, "' no termina con '", cadena2$, "'"
end if
end
</syntaxhighlight>
{{out}}
<pre>
'qwertyuiop' comienza con 'qwerty'
'qwertyuiop' contiene 'wert' en la posicion 2
'qwertyuiop' no termina con 'random garbage'
</pre>
=={{header|Z80 Assembly}}==
{{trans|MIPS Assembly}}
<syntaxhighlight lang="z80">InString:
;input: hl = pointer to string 1
; de = pointer to string 2
; assumes len(hl) <= len(de)
; output in BC
;clobbers: ix
push de
pop ix ;back up de into ix
ld bc,0 ;our return value
InString_again:
ld a,(hl)
or a
ret z
ld a,(de)
or a
ret z
cp (hl)
jr nz,InString_noMatch
inc de
jr InString_overhead
InString_noMatch:
push ix
pop de
inc bc
InString_overhead:
inc hl
jr InString_again</syntaxhighlight>
{{out}}
<syntaxhighlight lang="z80">org &1000
ld hl,TestString
ld de,Test1 ;recompiled with each test string and tested it
call InString
ld a,c
call ShowHex
ret
TestString:
db "abcdefg",0
Test1:
db "abc",0 ;returns 0
Test2:
db "def",0 ;returns 3
Test3:
db "efg",0 ;returns 4
Test4:
db "z",0 ;returns 7</syntaxhighlight>
=={{header|zkl}}==
<
f("foobar","foo") //--> Yep
f("foobar","bar") //--> Nope</
<
f("foobar","ob") //--> Contained @2
f("foobar","food") //--> Nope</
<
if( Void!=(n:=text.rfind(p)) and n+p.len()==text.len() )
println("tail gunner") else println("Nope")
Line 4,326 ⟶ 5,350:
f("foobar","r"); f("foobar","ar"); //--> tail gunners
f("foobar","ob"); //--> Nope
f("foobarfoobar","bar"); //--> tail gunner</
{{omit from|bc|No string operations in bc}}
|