String matching: Difference between revisions

m
 
(77 intermediate revisions by 49 users not shown)
Line 15:
::#   Print the location of the match for part 2
::#   Handle multiple occurrences of a string for part 2.
 
 
{{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}}==
<langsyntaxhighlight lang="360asm">* String matching 04/04/2017
STRMATCH CSECT
USING STRMATCH,R15
Line 51 ⟶ 74:
PG DC CL80' '
YREGS
END STRMATCH</langsyntaxhighlight>
{{out}}
<pre>
Line 63 ⟶ 86:
</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 */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessFound: .asciz "String found. \n"
szMessNotFound: .asciz "String not found. \n"
szString: .asciz "abcdefghijklmnopqrstuvwxyz"
szString2: .asciz "abc"
szStringStart: .asciz "abcd"
szStringEnd: .asciz "xyz"
szStringStart2: .asciz "abcd"
szStringEnd2: .asciz "xabc"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszString // address input string
ldr x1,qAdrszStringStart // address search string
bl searchStringDeb // Determining if the first string starts with second string
cmp x0,0
ble 1f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 2f
1:
ldr x0,qAdrszMessNotFound
bl affichageMess
2:
ldr x0,qAdrszString // address input string
ldr x1,qAdrszStringEnd // address search string
bl searchStringFin // Determining if the first string ends with the second string
cmp x0,0
ble 3f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 4f
3:
ldr x0,qAdrszMessNotFound
bl affichageMess
4:
ldr x0,qAdrszString2 // address input string
ldr x1,qAdrszStringStart2 // address search string
bl searchStringDeb //
cmp x0,0
ble 5f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 6f
5:
ldr x0,qAdrszMessNotFound
bl affichageMess
6:
ldr x0,qAdrszString2 // address input string
ldr x1,qAdrszStringEnd2 // address search string
bl searchStringFin
cmp x0,0
ble 7f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 8f
7:
ldr x0,qAdrszMessNotFound
bl affichageMess
8:
ldr x0,qAdrszString // address input string
ldr x1,qAdrszStringEnd // address search string
bl searchSubString // Determining if the first string contains the second string at any location
cmp x0,0
ble 9f
ldr x0,qAdrszMessFound // display message
bl affichageMess
b 10f
9:
ldr x0,qAdrszMessNotFound // display substring result
bl affichageMess
10:
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessFound: .quad szMessFound
qAdrszMessNotFound: .quad szMessNotFound
qAdrszString: .quad szString
qAdrszString2: .quad szString2
qAdrszStringStart: .quad szStringStart
qAdrszStringEnd: .quad szStringEnd
qAdrszStringStart2: .quad szStringStart2
qAdrszStringEnd2: .quad szStringEnd2
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* search substring at begin of input string */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of substring */
/* x0 returns 1 if find or 0 if not or -1 if error */
searchStringDeb:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,0 // counter byte string
ldrb w4,[x1,x3] // load first byte of substring
cbz x4,99f // empty string ?
1:
ldrb w2,[x0,x3] // load byte string input
cbz x2,98f // zero final ?
cmp x4,x2 // bytes equals ?
bne 98f // no not find
add x3,x3,1 // increment counter
ldrb w4,[x1,x3] // and load next byte of substring
cbnz x4,1b // zero final ?
mov x0,1 // yes is ok
b 100f
98:
mov x0,0 // not find
b 100f
99:
mov x0,-1 // error
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* search substring at end of input string */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of substring */
/* x0 returns 1 if find or 0 if not or -1 if error */
searchStringFin:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,0 // counter byte string
// search the last character of substring
1:
ldrb w4,[x1,x3] // load byte of substring
cmp x4,#0 // zero final ?
add x2,x3,1
csel x3,x2,x3,ne // no increment counter
//addne x3,#1 // no increment counter
bne 1b // and loop
cbz x3,99f // empty string ?
 
sub x3,x3,1 // index of last byte
ldrb w4,[x1,x3] // load last byte of substring
// search the last character of string
mov x2,0 // index last character
2:
ldrb w5,[x0,x2] // load first byte of substring
cmp x5,0 // zero final ?
add x5,x2,1 // no -> increment counter
csel x2,x5,x2,ne
//addne x2,#1 // no -> increment counter
bne 2b // and loop
cbz x2,98f // empty input string ?
sub x2,x2,1 // index last character
3:
ldrb w5,[x0,x2] // load byte string input
cmp x4,x5 // bytes equals ?
bne 98f // no -> not found
subs x3,x3,1 // decrement counter
blt 97f // ok found
subs x2,x2,1 // decrement counter input string
blt 98f // if zero -> not found
ldrb w4,[x1,x3] // load previous byte of substring
b 3b // and loop
97:
mov x0,1 // yes is ok
b 100f
98:
mov x0,0 // not found
b 100f
99:
mov x0,-1 // error
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* search a substring in the string */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of substring */
/* x0 returns index of substring in string or -1 if not found */
searchSubString:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x2,0 // counter byte input string
mov x3,0 // counter byte string
mov x6,-1 // index found
ldrb w4,[x1,x3]
1:
ldrb w5,[x0,x2] // load byte string
cbz x5,99f // zero final ?
cmp x5,x4 // compare character
beq 2f
mov x6,-1 // no equals - > raz index
mov x3,0 // and raz counter byte
add x2,x2,1 // and increment counter byte
b 1b // and loop
2: // characters equals
cmp x6,-1 // first characters equals ?
csel x6,x2,x6,eq // yes -> index begin in x6
//moveq x6,x2 // yes -> index begin in x6
add x3,x3,1 // increment counter substring
ldrb w4,[x1,x3] // and load next byte
cmp x4,0 // zero final ?
beq 3f // yes -> end search
add x2,x2,1 // else increment counter string
b 1b // and loop
3:
mov x0,x6
b 100f
 
98:
mov x0,0 // not found
b 100f
99:
mov x0,-1 // error
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* 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">
<lang Ada>
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
Line 86 ⟶ 487:
);
end Match_Strings;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 96 ⟶ 497:
 
=={{header|Aime}}==
<syntaxhighlight lang ="aime">text s, t;
data b;
 
sb = "Bangkok";
t = "Bang";
 
t = "Bang";
b_cast(b, s);
 
o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b_seek(b, .seek(t) == 0,
b_seek(b, .seek(t) != -1,
b_seekb.seek(b, t) != -1 && b_seekb.seek(b, t) + length(~t) == length(s)~b);
 
t = "ok";
 
o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b_seek(b, .seek(t) == 0,
b_seek(b, .seek(t) != -1,
b_seekb.seek(b, t) != -1 && b_seekb.seek(b, t) + length(~t) == length(s)~b);
 
t = "Summer";
 
o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b_seek(b, .seek(t) == 0,
b_seek(b, .seek(t) != -1,
b_seekb.seek(b, t) != -1 && b_seekb.seek(b, t) + length(~t) == length(s)~b);</langsyntaxhighlight>
{{out}}
<pre>starts with, embeds, ends with "Bang": 1, 1, 0
Line 129 ⟶ 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?}}
<langsyntaxhighlight lang="algol68"># define some appropriate OPerators #
PRIO STARTSWITH = 5, ENDSWITH = 5;
OP STARTSWITH = (STRING str, prefix)BOOL: # assuming LWB = 1 #
Line 146 ⟶ 546:
(string in string("ab",loc,"abab")|loc|-1), # returns +1 #
(string in string("ab",loc2,"abab"[loc+1:])|loc+loc2|-1) # returns +3 #
))</langsyntaxhighlight>
{{out}}
<pre>
TFFT -1 +1 +3
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">set stringA to "I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy."
 
set string1 to "I felt happy"
set string2 to "I should feel happy"
set string3 to "I wasn't really happy"
 
-- Determining if the first string starts with second string
stringA starts with string1 --> true
 
-- Determining if the first string contains the second string at any location
stringA contains string2 --> true
 
-- Determining if the first string ends with the second string
stringA ends with string3 --> false
 
-- Print the location of the match for part 2
offset of string2 in stringA --> 69</syntaxhighlight>
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:
<syntaxhighlight lang="applescript">-- Handle multiple occurrences of a string for part 2
on offset of needle in haystack
local needle, haystack
if the needle is not in the haystack then return {}
set my text item delimiters to the needle
script
property N : needle's length
property t : {1 - N} & haystack's text items
end script
tell the result
repeat with i from 2 to (its t's length) - 1
set x to item i of its t
set y to item (i - 1) of its t
set item i of its t to (its N) + (x's length) + y
end repeat
items 2 thru -2 of its t
end tell
end offset
 
offset of "happy" in stringA --> {8, 44, 83, 110}</syntaxhighlight>
 
 
or, defining an '''offsets''' function in terms of a more general '''findIndices''':
<syntaxhighlight lang="applescript">-- offsets :: String -> String -> [Int]
on offsets(needle, haystack)
script match
property mx : length of haystack
property d : (length of needle) - 1
on |λ|(x, i, xs)
set z to d + i
mx ≥ z and needle = text i thru z of xs
end |λ|
end script
findIndices(match, haystack)
end offsets
 
 
-- TEST ---------------------------------------------------
on run
set txt to "I felt happy because I saw the others " & ¬
"were happy and because I knew I should " & ¬
"feel happy, but I wasn’t really happy."
offsets("happy", txt)
--> {8, 44, 83, 110}
end run
 
 
-- GENERIC -------------------------------------------------
 
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & (|λ|(item i of xs, i, xs))
end repeat
end tell
return acc
end concatMap
 
 
-- findIndices :: (a -> Bool) -> [a] -> [Int]
-- findIndices :: (String -> Bool) -> String -> [Int]
on findIndices(p, xs)
script go
property f : mReturn(p)
on |λ|(x, i, xs)
if f's |λ|(x, i, xs) then
{i}
else
{}
end if
end |λ|
end script
concatMap(go, xs)
end findIndices
 
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn</syntaxhighlight>
{{Out}}
<pre>{8, 44, 83, 110}</pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program strMatching.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
 
/* Initialized data */
.data
szMessFound: .asciz "String found. \n"
szMessNotFound: .asciz "String not found. \n"
szString: .asciz "abcdefghijklmnopqrstuvwxyz"
szString2: .asciz "abc"
szStringStart: .asciz "abcd"
szStringEnd: .asciz "xyz"
szStringStart2: .asciz "abcd"
szStringEnd2: .asciz "xabc"
szCarriageReturn: .asciz "\n"
 
/* UnInitialized data */
.bss
 
/* code section */
.text
.global main
main:
 
ldr r0,iAdrszString @ address input string
ldr r1,iAdrszStringStart @ address search string
 
bl searchStringDeb @ Determining if the first string starts with second string
cmp r0,#0
ble 1f
ldr r0,iAdrszMessFound @ display message
bl affichageMess
b 2f
1:
ldr r0,iAdrszMessNotFound
bl affichageMess
2:
ldr r0,iAdrszString @ address input string
ldr r1,iAdrszStringEnd @ address search string
bl searchStringFin @ Determining if the first string ends with the second string
cmp r0,#0
ble 3f
ldr r0,iAdrszMessFound @ display message
bl affichageMess
b 4f
3:
ldr r0,iAdrszMessNotFound
bl affichageMess
4:
ldr r0,iAdrszString2 @ address input string
ldr r1,iAdrszStringStart2 @ address search string
 
bl searchStringDeb @
cmp r0,#0
ble 5f
ldr r0,iAdrszMessFound @ display message
bl affichageMess
b 6f
5:
ldr r0,iAdrszMessNotFound
bl affichageMess
6:
ldr r0,iAdrszString2 @ address input string
ldr r1,iAdrszStringEnd2 @ address search string
bl searchStringFin
cmp r0,#0
ble 7f
ldr r0,iAdrszMessFound @ display message
bl affichageMess
b 8f
7:
ldr r0,iAdrszMessNotFound
bl affichageMess
8:
ldr r0,iAdrszString @ address input string
ldr r1,iAdrszStringEnd @ address search string
bl searchSubString @ Determining if the first string contains the second string at any location
cmp r0,#0
ble 9f
ldr r0,iAdrszMessFound @ display message
bl affichageMess
b 10f
9:
ldr r0,iAdrszMessNotFound @ display substring result
bl affichageMess
10:
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessFound: .int szMessFound
iAdrszMessNotFound: .int szMessNotFound
iAdrszString: .int szString
iAdrszString2: .int szString2
iAdrszStringStart: .int szStringStart
iAdrszStringEnd: .int szStringEnd
iAdrszStringStart2: .int szStringStart2
iAdrszStringEnd2: .int szStringEnd2
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* search substring at begin of input string */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of substring */
/* r0 returns 1 if find or 0 if not or -1 if error */
searchStringDeb:
push {r1-r4,lr} @ save registers
mov r3,#0 @ counter byte string
ldrb r4,[r1,r3] @ load first byte of substring
cmp r4,#0 @ empty string ?
moveq r0,#-1 @ error
beq 100f
1:
ldrb r2,[r0,r3] @ load byte string input
cmp r2,#0 @ zero final ?
moveq r0,#0 @ not find
beq 100f
cmp r4,r2 @ bytes equals ?
movne r0,#0 @ no not find
bne 100f
add r3,#1 @ increment counter
ldrb r4,[r1,r3] @ and load next byte of substring
cmp r4,#0 @ zero final ?
bne 1b @ no -> loop
mov r0,#1 @ yes is ok
100:
pop {r1-r4,lr} @ restaur registers
bx lr @ return
 
/******************************************************************/
/* search substring at end of input string */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of substring */
/* r0 returns 1 if find or 0 if not or -1 if error */
searchStringFin:
push {r1-r5,lr} @ save registers
mov r3,#0 @ counter byte string
@ search the last character of substring
1:
ldrb r4,[r1,r3] @ load byte of substring
cmp r4,#0 @ zero final ?
addne r3,#1 @ no increment counter
bne 1b @ and loop
cmp r3,#0 @ empty string ?
moveq r0,#-1 @ error
beq 100f
sub r3,#1 @ index of last byte
ldrb r4,[r1,r3] @ load last byte of substring
@ search the last character of string
mov r2,#0 @ index last character
2:
ldrb r5,[r0,r2] @ load first byte of substring
cmp r5,#0 @ zero final ?
addne r2,#1 @ no -> increment counter
bne 2b @ and loop
cmp r2,#0 @ empty input string ?
moveq r0,#0 @ yes -> not found
beq 100f
sub r2,#1 @ index last character
3:
ldrb r5,[r0,r2] @ load byte string input
cmp r4,r5 @ bytes equals ?
movne r0,#0 @ no -> not found
bne 100f
subs r3,#1 @ decrement counter
movlt r0,#1 @ if zero -> ok found
blt 100f
subs r2,#1 @ decrement counter input string
movlt r0,#0 @ if zero -> not found
blt 100f
ldrb r4,[r1,r3] @ load previous byte of substring
b 3b @ and loop
100:
pop {r1-r5,lr} @ restaur registers
bx lr @ return
 
/******************************************************************/
/* search a substring in the string */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of substring */
/* r0 returns index of substring in string or -1 if not found */
searchSubString:
push {r1-r6,lr} @ save registers
mov r2,#0 @ counter byte input string
mov r3,#0 @ counter byte string
mov r6,#-1 @ index found
ldrb r4,[r1,r3]
1:
ldrb r5,[r0,r2] @ load byte string
cmp r5,#0 @ zero final ?
moveq r0,#-1 @ yes returns error
beq 100f
cmp r5,r4 @ compare character
beq 2f
mov r6,#-1 @ no equals - > raz index
mov r3,#0 @ and raz counter byte
add r2,#1 @ and increment counter byte
b 1b @ and loop
2: @ characters equals
cmp r6,#-1 @ first characters equals ?
moveq r6,r2 @ yes -> index begin in r6
add r3,#1 @ increment counter substring
ldrb r4,[r1,r3] @ and load next byte
cmp r4,#0 @ zero final ?
beq 3f @ yes -> end search
add r2,#1 @ else increment counter string
b 1b @ and loop
3:
mov r0,r6
100:
pop {r1-r6,lr} @ restaur registers
bx lr
 
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
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" "ab"
print contains? "abcd" "xy"
 
print in? "ab" "abcd"
print in? "xy" "abcd"
 
print index "abcd" "bc"
print index "abcd" "xy"</syntaxhighlight>
 
{{out}}
 
<pre>true
false
false
true
true
false
true
false
1
null</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
<lang AutoHotkey>
String1 = abcd
String2 = abab
Line 168 ⟶ 960:
If TempVar = %String2%
MsgBox, "%String1%" ends with "%String2%".
</syntaxhighlight>
</lang>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">$string1 = "arduinoardblobard"
$string2 = "ard"
 
Line 201 ⟶ 993:
EndIf
 
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
{ pos=index($2,$1)
{
print $2, (pos==1 ? "begins" : "does not begin" ), "with " $1
if ($1 ~ "^"$2) {
print $2, (pos ? "contains an" : "does not contain" ), "\"" $1 "\""
print $1" begins with "$2;
if (pos) {
} else {
l=length($1)
print $1" does not begin with "$2;
Pos=pos
}
s=$2
 
if while ($1 ~ $2Pos) {
print " " $1 " containsis at index"$2;, x+Pos
x+=Pos
} else {
s=substr(s,Pos+l)
print $1" does not contain "$2;
Pos=index(s,$1)
}
}
 
}
if ($1 ~ $2"$") {
print $2, (substr($2,pos)==$1" ? "ends" : "does not end"), "with " $2;1
} else {
print $1" does not end with "$2;
}
}
</syntaxhighlight>
</lang>
 
 
=={{header|BASIC}}==
{{works with|QBasic}}
<langsyntaxhighlight lang="qbasic">first$ = "qwertyuiop"
 
'Determining if the first string starts with second string
Line 257 ⟶ 1,045:
END IF
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 265 ⟶ 1,053:
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 A$ = "THIS, THAT, AND THE OTHER THING"
20 S$ = "TH"
30 DEF FN S(P) = MID$(A$, P, LEN(S$)) = S$
Line 282 ⟶ 1,070:
310 E$(1) = "ENDS"
320 E$(0) = "DOES NOT END"
330 PRINT E$(FN S(LEN(A$) - LEN(S$) + 1))" WITH "S$</langsyntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">::NOTE #1: This implementation might crash, or might not work properly if
::you put some of the CMD special characters (ex. %,!, etc) inside the strings.
::
Line 354 ⟶ 1,142:
set /a length+=1
goto loop
::/The functions.</langsyntaxhighlight>
{{out}}
<pre>"qwertyuiop" begins with "qwerty".
Line 366 ⟶ 1,154:
 
Press any key to continue . . .</pre>
 
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> first$ = "The fox jumps over the dog"
FOR test% = 1 TO 3
Line 401 ⟶ 1,188:
UNTIL I% = 0
= N%
</syntaxhighlight>
</lang>
{{out}}
<pre>"The fox jumps over the dog" starts with "The"
Line 411 ⟶ 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.
<langsyntaxhighlight Bracmatlang="bracmat">( (sentence="I want a number such that that number will be even.")
& 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 422 ⟶ 1,239:
| out$str$("sentence contains " !N " occurrences of 'be'")
)
)</langsyntaxhighlight>
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 436 ⟶ 1,253:
=={{header|C}}==
Case sensitive matching:
<langsyntaxhighlight Clang="c">#include <string.h>
#include <stdio.h>
 
Line 467 ⟶ 1,284:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Starts with Test ( Hello,Hell ) : 1
Line 473 ⟶ 1,290:
Contains Test ( Google,msn ) : 0</pre>
Code without using string library to demonstrate how char strings are just pointers:
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
/* returns 0 if no match, 1 if matched, -1 if matched and at end */
Line 516 ⟶ 1,333:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>matching `A Short String' with `ort S':
Line 530 ⟶ 1,347:
matching `something random' with `Rand':
end match</pre>
 
=={{header|C++}}==
<lang cpp>#include <string>
using namespace std;
 
string s1="abcd";
string s2="abab";
string s3="ab";
//Beginning
s1.compare(0,s3.size(),s3)==0;
//End
s1.compare(s1.size()-s3.size(),s3.size(),s3)==0;
//Anywhere
s1.find(s2)//returns string::npos
int loc=s2.find(s3)//returns 0
loc=s2.find(s3,loc+1)//returns 2</lang>
 
=={{header|C sharp|C#}}==
{{works with|Mono|2.6}}
<langsyntaxhighlight lang="csharp">
class Program
{
Line 563 ⟶ 1,364:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <string>
using namespace std;
 
string s1="abcd";
string s2="abab";
string s3="ab";
//Beginning
s1.compare(0,s3.size(),s3)==0;
//End
s1.compare(s1.size()-s3.size(),s3.size(),s3)==0;
//Anywhere
s1.find(s2)//returns string::npos
int loc=s2.find(s3)//returns 0
loc=s2.find(s3,loc+1)//returns 2</syntaxhighlight>
 
=={{header|Clojure}}==
{{trans|Java}}
<langsyntaxhighlight lang="clojure">(def evals '((. "abcd" startsWith "ab")
(. "abcd" endsWith "zn")
(. "abab" contains "bb")
Line 576 ⟶ 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])</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
Line 582 ⟶ 1,399:
This example uses string slices, but a better implementation might use indexOf for slightly better performance.
 
<langsyntaxhighlight lang="coffeescript">
matchAt = (s, frag, i) ->
s[i...i+frag.length] == frag
Line 603 ⟶ 1,420:
console.log matchLocations "bababab", "bab" # [0,2,4]
console.log matchLocations "xxx", "x" # [0,1,2]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun starts-with-p (str1 str2)
"Determine whether `str1` starts with `str2`"
Line 635 ⟶ 1,452:
(print (containsp "ababaBa" "ba")) ; (1 3)
(print (containsp "foobar" "x")) ; NIL
</syntaxhighlight>
</lang>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE StringMatch;
IMPORT StdLog,Strings;
Line 753 ⟶ 1,570:
END Do;
END StringMatch.
</syntaxhighlight>
</lang>
Execute: ^Q StringMatching.Do <br/>
{{out}}
Line 778 ⟶ 1,595:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio;
import std.algorithm: startsWith, endsWith, find, countUntil;
Line 793 ⟶ 1,610:
[1, 2, 3].countUntil(3).writeln; // 2
[1, 2, 3].countUntil([2, 3]).writeln; // 1
}</langsyntaxhighlight>
{{out}}
<pre>true
Line 803 ⟶ 1,620:
2
1</pre>
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ first_string = p1
$ length_of_first_string = f$length( first_string )
$ second_string = p2
Line 827 ⟶ 1,645:
$ else
$ write sys$output "first string does not end with the second string"
$ endif</langsyntaxhighlight>
{{out}}
<pre>$ @string_matching efabcdef ef
Line 847 ⟶ 1,665:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program CharacterMatching;
 
{$APPTYPE CONSOLE}
Line 859 ⟶ 1,677:
Writeln(AnsiContainsText('abcd', 'ab')); // True
WriteLn(Pos('ab', 'abcd')); // 1
end.</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">var value = "abcd".StartsWith("ab")
value = "abcd".EndsWith("zn") //returns false
value = "abab".Contains("bb") //returns false
value = "abab".Contains("ab") //returns true
var loc = "abab".IndexOf("bb") //returns -1
loc = "abab".IndexOf("ab") //returns 0</syntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def f(string1, string2) {
println(string1.startsWith(string2))
Line 873 ⟶ 1,700:
 
println(string1.endsWith(string2))
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(string-suffix? "nette" "Antoinette") → #t
(string-prefix? "Simon" "Simon & Garfunkel") → #t
Line 882 ⟶ 1,709:
(string-match "Antoinette" "net") → #t ;; contains
(string-index "net" "Antoinette") → 5 ;; substring location
</syntaxhighlight>
</lang>
 
=={{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|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
public program()
Line 892 ⟶ 1,742:
var s := "abcd";
console.printLine(s," starts with ab: ",s.startingWith:("ab"));
console.printLine(s," starts with cd: ",s.startingWith:("cd"));
console.printLine(s," ends with ab: ",s.endingWith:("ab"));
console.printLine(s," ends with cd: ",s.endingWith:("cd"));
console.printLine(s," contains ab: ",s.containing:("ab"));
console.printLine(s," contains bc: ",s.containing:("bc"));
console.printLine(s," contains cd: ",s.containing:("cd"));
console.printLine(s," contains az: ",s.containing:("az"));
console.printLine(s," index of az: ",s.indexOf(0, "az"));
Line 909 ⟶ 1,759:
console.readChar()
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
The String module has functions that cover the base requirements.
<langsyntaxhighlight lang="elixir">s1 = "abcd"
s2 = "adab"
s3 = "ab"
Line 940 ⟶ 1,790:
 
Regex.scan(~r/#{s3}/, "abcabc", return: :index)
# => [[{0, 2}], [{3, 2}]]</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun string-contains (needle haystack)
<lang Emacs Lisp>
(string-match (regexp-quote needle) haystack))
(defun match (word str)
(progn
(setq regex (format "^%s.*$" word) )
(if (string-match regex str)
(insert (format "%s found in beginning of: %s\n" word str) )
(insert (format "%s not found in beginning of: %s\n" word str) ))
 
(string-prefix-p "before" "before center after") ;=> t
(setq pos (string-match word str) )
(string-contains "before" "before center after") ;=> 0
(string-suffix-p "before" "before center after") ;=> nil
 
(string-prefix-p "center" "before center after") ;=> nil
(if pos
(string-contains "center" "before center after") ;=> 7
(insert (format "%s found at position %d in: %s\n" word pos str) )
(string-suffix-p "center" "before center after") ;=> nil
(insert (format "%s not found in: %s\n" word str) ))
(setq regex (format "^.*%s$" word) )
(if (string-match regex str)
(insert (format "%s found in end of: %s\n" word str) )
(insert (format "%s not found in end of: %s\n" word str) ))))
 
(setq string-prefix-p "after" "before center after") ;=> nil
(string-contains "after" "before center after") ;=> 14
 
(string-suffix-p "after" "before center after") ;=> t</syntaxhighlight>
(progn
(match "center" string)
(insert "\n")
(match "before" string)
(insert "\n")
(match "after" string) )
</lang>
<b>Output:</b>
<pre>
center not found in beginning of: before center after
center found at position 7 in: before center after
center not found in end of: before center after
 
before found in beginning of: before center after
before found at position 0 in: before center after
before not found in end of: before center after
 
after not found in beginning of: before center after
after found at position 14 in: before center after
after found in end of: before center after
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(character_matching).
-export([starts_with/2,ends_with/2,contains/2]).
Line 1,019 ⟶ 1,838:
contains(_S1,_S2,_N,Acc) ->
Acc.
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">sequence first, second
integer x
 
Line 1,050 ⟶ 1,870:
else
printf(1, "'%s' does not end with '%s'\n", {first, second})
end if</langsyntaxhighlight>
 
{{out}}
Line 1,059 ⟶ 1,879:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">[<EntryPoint>]
let main args =
 
Line 1,082 ⟶ 1,902:
if idx < 0 then None else Some (idx, idx+1)) 0
|> Seq.iter (printfn "substring %A begins at position %d (zero-based)" contains)
0</langsyntaxhighlight>
{{out}}
<pre>text = "一二三四五六七八九十"
Line 1,098 ⟶ 1,918:
=={{header|Factor}}==
Does <code>cheesecake</code> start with <code>cheese</code>?
<langsyntaxhighlight lang="factor">"cheesecake" "cheese" head? ! t</langsyntaxhighlight>
Does <code>cheesecake</code> contain <code>sec</code> at any location?
<langsyntaxhighlight lang="factor">"sec" "cheesecake" subseq? ! t</langsyntaxhighlight>
Does <code>cheesecake</code> end with <code>cake</code>?
<langsyntaxhighlight lang="factor">"cheesecake" "cake" tail? ! t</langsyntaxhighlight>
Where in <code>cheesecake</code> is the leftmost <code>sec</code>?
<langsyntaxhighlight lang="factor">"sec" "cheesecake" subseq-start ! 4</langsyntaxhighlight>
Where in <code>Mississippi</code> are all occurrences of <code>iss</code>?
<langsyntaxhighlight lang="factor">USE: regexp
"Mississippi" "iss" <regexp> all-matching-slices [ from>> ] map ! { 1 4 }</langsyntaxhighlight>
 
=={{header|Falcon}}==
'''VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems falconic''
<langsyntaxhighlight lang="falcon">
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 1,126 ⟶ 1,946:
 
> s1.endsWith(s2) ? @ "s1 ends with $s2" : @ "$s1 does not end with $s2"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,147 ⟶ 1,967:
* <code>indexrIgnoreCase</code> (like above, ignoring case for ASCII characters)
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,170 ⟶ 1,990:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,188 ⟶ 2,008:
 
=={{header|FBSL}}==
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
DIM s = "roko, mat jane do"
Line 1,203 ⟶ 2,023:
WHILE INSTR(mane, match, INSTR + 1): PRINT " ", INSTR;: WEND
END SUB
</syntaxhighlight>
</lang>
{{out}}
<pre>"roko, mat jane do" starts with "roko"
Line 1,213 ⟶ 2,033:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: starts-with ( a l a2 l2 -- ? )
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</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,226 ⟶ 2,046:
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">
<lang Fortran>
SUBROUTINE STARTS(A,B) !Text A starts with text B?
CHARACTER*(*) A,B
Line 1,267 ⟶ 2,087:
CALL ENDS("Brief","Much longer")
END
</syntaxhighlight>
</lang>
Output: text strings are bounded by >''etc.''< in case of leading or trailing spaces.
<pre>
Line 1,279 ⟶ 2,099:
 
Similar program using modern Fortran style
<syntaxhighlight lang="fortran">
<lang Fortran>
!-----------------------------------------------------------------------
!Main program string_matching
Line 1,342 ⟶ 2,162:
end function ends
end program string_matching
</syntaxhighlight>
</lang>
Output: false = 0, true = 1 ( + multiple occurrences if applicable)
<pre>
Line 1,357 ⟶ 2,177:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim As String s1 = "abracadabra"
Line 1,382 ⟶ 2,202:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,392 ⟶ 2,212:
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]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sString1 As String = "Hello world"
Dim sString2 As String = "Hello"
Line 1,404 ⟶ 2,320:
Print sString1 Ends Left(sString2, 5) 'Determine if the first string ends with the second string
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,411 ⟶ 2,327:
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}}
 
<langsyntaxhighlight GMLlang="gml">#define charMatch
{
first = "qwertyuiop";
Line 1,449 ⟶ 2,383:
show_message("'" + first + "' does not end with '" + second + "'");
}
}</langsyntaxhighlight>
 
{{out}} (in message boxes, 1 per line):
Line 1,458 ⟶ 2,392:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,487 ⟶ 2,421:
func main() {
match("abracadabra", "abr")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,500 ⟶ 2,434:
=={{header|Groovy}}==
Examples:
<langsyntaxhighlight lang="groovy">assert "abcd".startsWith("ab")
assert ! "abcd".startsWith("zn")
assert "abcd".endsWith("cd")
Line 1,522 ⟶ 2,456:
assert indicesOf("abab", "ab") == [0, 2]
assert indicesOf("abab", "ba") == [1]
assert indicesOf("abab", "xy") == []</langsyntaxhighlight>
 
All assertions pass, so there is no output.
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">> import Data.List
> "abc" `isPrefixOf` "abcdefg"
True
Line 1,538 ⟶ 2,472:
> let infixes a b = findIndices (isPrefixOf a) $ tails b
> infixes "ab" "abcdefabqqab"
[0,6,10]</langsyntaxhighlight>
 
== {{header|Icon}} and {{header|Unicon}} ==
<langsyntaxhighlight Iconlang="icon">procedure main()
 
write("Matching s2 :=",image(s2 := "ab")," within s1:= ",image(s1 := "abcdabab"))
Line 1,550 ⟶ 2,484:
write("Test #3 ending ", if s1[0-:*s2] == s2 then "matches" else "fails")
end</langsyntaxhighlight>
 
{{out}}
Line 1,559 ⟶ 2,493:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">startswith=: ] -: ({.~ #)
contains=: +./@:E.~
endswith=: ] -: ({.~ -@#)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> 'abcd' startswith 'ab'
1
'abcd' startswith 'cd'
Line 1,582 ⟶ 2,516:
1
'abab' I.@E.~ 'ab' NB. find starting indicies
0 2</langsyntaxhighlight>
 
Note that these verbs contain no constraints restricting them to sequences of characters and so also apply to arrays of type other than character:
<langsyntaxhighlight lang="j"> 0 1 2 3 startswith 0 1 NB. integer
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</langsyntaxhighlight>
 
=={{header|Java}}==
For this task consider the following strings
<lang java>"abcd".startsWith("ab") //returns true
<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 1,599 ⟶ 2,577:
int loc = "abab".indexOf("bb") //returns -1
loc = "abab".indexOf("ab") //returns 0
loc = "abab".indexOf("ab",loc+1) //returns 2</lang>
</syntaxhighlight>
 
<syntaxhighlight lang="java">
// -----------------------------------------------------------//
public class JavaApplication6 {
 
public static void main(String[] args) {
String strOne = "complexity";
String strTwo = "udacity";
 
//
stringMatch(strOne, strTwo);
 
}
 
Line 1,638 ⟶ 2,612:
}
}
</syntaxhighlight>
 
=={{header|JavaScript}}==
 
<langsyntaxhighlight lang="javascript">var stringA = "tacoloco"
, stringB = "co"
, q1, q2, q2multi, m
Line 1,667 ⟶ 2,642:
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."))</langsyntaxhighlight>
 
{{out}}
Line 1,674 ⟶ 2,649:
In fact, it happens 2 times within 'tacoloco', at indexes 2, 6.
3: Does 'tacoloco' end with 'co'? Yes.</pre>
 
 
=={{header|jq}}==
Using the builtins of jq 1.4 and later:
<langsyntaxhighlight lang="jq"># startswith/1 is boolean:
"abc" | startswith("ab")
#=> true</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq"># index/1 returns the index or null,
# so the jq test "if index(_) then ...." can be used
# without any type conversion.
 
"abcd" | index( "bc")
#=> 1</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq"># endswith/1 is also boolean:
"abc" | endswith("bc")
#=> true</langsyntaxhighlight>
 
Using the regex functions available in jq 1.5:
<langsyntaxhighlight lang="jq">"abc" | test( "^ab")
 
"abcd" | test("bc")
 
"abcd" | test("cd$")</langsyntaxhighlight>
 
===Multiple Occurrences===
To determine all the indices of one string in another:
<langsyntaxhighlight lang="sh"># In jq 1.4 or later:
jq -n '"abcdabcd" | indices("bc")'
[
1,
5
]</langsyntaxhighlight>
 
In jq 1.5, the regex function match/1 can also be used:
<langsyntaxhighlight lang="sh">$ jq -n '"abcdabcd" | match("bc"; "g") | .offset'
1
5</langsyntaxhighlight>
 
 
=={{header|Julia }}==
<langsyntaxhighlight lang="julia">
startswith("abcd","ab") #returns true
findfirst("ab", "abcd") #returns 1:2, indices range where string was found
Line 1,724 ⟶ 2,697:
println(r.offset)
end #returns 1, then 3 matching the two starting indices where the substring was found
</syntaxhighlight>
</lang>
 
 
=={{header|K}}==
<langsyntaxhighlight lang="k">startswith: {:[0<#p:_ss[x;y];~*p;0]}
endswith: {0=(-#y)+(#x)-*_ss[x;y]}
contains: {0<#_ss[x;y]}</langsyntaxhighlight>
 
'''Example:'''
 
<langsyntaxhighlight lang="k"> startswith["abcd";"ab"]
1
startswith["abcd";"bc"]
Line 1,747 ⟶ 2,719:
0
_ss["abcdabceabc";"abc"] / location of matches
0 4 8</langsyntaxhighlight>
 
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
<lang scala>// version 1.0.6
fun main() {
 
fun main(args: Array<String>) {
val s1 = "abracadabra"
val s2 = "abra"
println("$s1 begins with $s2 : ${s1.startsWith(s2)}")
println("$s1 ends with $s2 : ${s1.endsWith(s2)}")
val b = s2 in s1
if (b) {
print("$s1 contains $s2 : $b")
print("$s1 contains $s2 at these indices: ")
if (b) println(" at locations ${s1.indexOf(s2) + 1} and ${s1.lastIndexOf(s2) + 1}")
// can use indexOf to get first index or lastIndexOf to get last index
else println()
// to get ALL indices, use a for loop or Regex
}</lang>
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 : true
abracadabra ends with abra : true
abracadabra contains abra at these indices: true at locations 1 and0, 87
</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 1,777 ⟶ 2,866:
[[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
 
=={{header|Lasso}}==
 
<lang Lasso>local(
a = 'a quick brown peanut jumped over a quick brown fox',
b = 'a quick brown'
)
 
{def startswith
//Determining if the first string starts with second string
{lambda {:w1 :w2}
#a->beginswith(#b) // true
{= {S.in _ {S.replace :w2 by _ in :w1}} 0}}}
-> startswith
 
{def endswith
//Determining if the first string contains the second string at any location
{lambda {:w1 :w2}
#a >> #b // true
{= {S.in _ {S.replace :w2 by _ in :w1}}
#a->contains(#b) // true
{- {W.length :w1} {W.length :w2}}}}}
-> endswith
 
{def isin
//Determining if the first string ends with the second string
{lambda {:w1 :w2}
#a->endswith(#b) // false</lang>
{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}}==
<langsyntaxhighlight lang="lang5">: 2array 2 compress ; : bi* '_ set dip _ execute ; : bi@ dup bi* ;
: comb "" split ; : concat "" join ; : dip swap '_ set execute _ ;
: first 0 extract swap drop ; : flip comb reverse concat ;
Line 1,815 ⟶ 2,934:
"rosettacode" "ocat" contains . # 0
"rosettacode" "edoc" end-with . # 0
"rosettacode" "code" contains . # 7</langsyntaxhighlight>
 
=={{header|Lasso}}==
 
<syntaxhighlight lang="lasso">local(
a = 'a quick brown peanut jumped over a quick brown fox',
b = 'a quick brown'
)
 
//Determining if the first string starts with second string
#a->beginswith(#b) // true
 
//Determining if the first string contains the second string at any location
#a >> #b // true
#a->contains(#b) // true
 
//Determining if the first string ends with the second string
#a->endswith(#b) // false</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">'1---Determining if the first string starts with second string
st1$="first string"
st2$="first"
Line 1,848 ⟶ 2,984:
print "First string ends with second string."
end if
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">a = "Hello world!"
b = "Hello"
 
Line 1,872 ⟶ 3,008:
-- Print the location of the match for part 2
put offset(b, a)
-- 7</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to starts.with? :sub :thing
if empty? :sub [output "true]
if empty? :thing [output "false]
Line 1,891 ⟶ 3,027:
show starts.with? "dog "doghouse ; true
show ends.with? "house "doghouse ; true
show substring? "gho "doghouse ; true (built-in)</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">s1 = "string"
s2 = "str"
s3 = "ing"
Line 1,905 ⟶ 3,042:
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 ) )</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module StringMatch {
A$="Hello World"
Line 1,922 ⟶ 3,060:
Print A$ ~ "*orld"
}
StringMatch
</syntaxhighlight>
{{out}}
<pre>
Line 1,931 ⟶ 3,071:
True
</pre>
 
StringMatch
</lang>
=={{header|Maple}}==
These facilities are all to be found in the StringTools package in Maple.
<syntaxhighlight lang="maple">
<lang Maple>
> with( StringTools ): # bind package exports at the top-level
> s := "dzrIemaWWIMidXYZwGiqkOOn":
Line 1,967 ⟶ 3,106:
> {seq}( s[ i .. i + 2 ], i = p ); # check them
{"XYZ"}
</syntaxhighlight>
</lang>
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}}==
<langsyntaxhighlight Mathematicalang="mathematica">StartWith[x_, y_] := MemberQ[Flatten[StringPosition[x, y]], 1]
EndWith[x_, y_] := MemberQ[Flatten[StringPosition[x, y]], StringLength[x]]
StartWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"]
EndWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"]
StringPosition["XYZaaabXYZaaaaXYZXYZ", "XYZ"]</langsyntaxhighlight>
{{out}}
<pre>True
True
{{1,3},{8,10},{15,17},{18,20}}</pre>
 
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
% 1. Determining if the first string starts with second string
strcmp(str1,str2,length(str2))
Line 1,995 ⟶ 3,133:
% 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>
</lang>
 
=={{header|min}}==
One way might be:
{{works with|min|0.19.6}}
<syntaxhighlight lang="min">(indexof 0 ==) :starts-with?
(indexof -1 !=) :contains?
((/ $/) swap 1 insert "" join regex ("") !=) :ends-with?
 
"minimalistic" "min" starts-with? puts!
"minimalistic" "list" contains? puts!
"minimalistic" "list" ends-with? puts!</syntaxhighlight>
{{out}}
<pre>
true
true
false
</pre>
 
=={{header|MiniScript}}==
We first extend the built-in string class with three new methods, and then demonstrate their use on some sample strings.
 
<syntaxhighlight lang="miniscript">string.startsWith = function(s)
return self.len >= s.len and s[:s.len] == s
end function
 
string.endsWith = function(s)
return self.len >= s.len and s[-s.len:] == s
end function
 
string.findAll = function(s)
result = []
after = null
while true
foundPos = self.indexOf(s, after)
if foundPos == null then return result
result.push foundPos
after = foundPos + s.len - 1
end while
end function
first = "The brown dog jumped jumped and jumped"
second = "jumped"
 
firstQ = """" + first + """" // (first string, in quotes)
secondQ = """" + second + """"
doesOrNot = [" does not ", " does "]
 
print firstQ + doesOrNot[first.startsWith(second)] + "start with " + secondQ
print
 
found = first.findAll(second)
if not found then
print firstQ + " does not contain " + secondQ + " anywhere"
else
for pos in found
print firstQ + " is found at position " + pos + " in " + secondQ
end for
end if
print
 
print firstQ + doesOrNot[first.endsWith(second)] + "end with " + secondQ</syntaxhighlight>
{{out}}
<pre>
"The brown dog jumped jumped and jumped" does start with "jumped"
"The brown dog jumped jumped and jumped" is found at position 14 in "jumped"
"The brown dog jumped jumped and jumped" is found at position 21 in "jumped"
"The brown dog jumped jumped and jumped" is found at position 32 in "jumped"
"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}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols
 
Line 2,047 ⟶ 3,343:
 
return
</syntaxhighlight>
</lang>
 
----
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(setq str "abcdefbcghi")
 
;; test if str starts with "ab"
Line 2,068 ⟶ 3,365:
(push idx pos -1))))
 
(find-all-pos "bc" str)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
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>
 
var s: string = "The quick brown fox"
if startsWith(s, "The quick"):
echo("Starts with: The quick")
if endsWith(s, "brown Fox"):
echo("Ends with: brown fox")
var pos = find(s, " brown ") # -1 if not found
if contains(s, " brown "): # showing the contains() proc, but could use if pos!=-1:
echo('"' & " brown " & '"' & " is located at position: " & $pos)</lang>
{{out}}
<pre>Starts with: The“The quickquick”.
EndsContains with: brown fox”.
Contains “quick”.
" brown " is located at position: 9</pre>
“ brown ” is located at position: 9</pre>
 
=={{header|Objective-C}}==
<lang objc>[@"abcd" hasPrefix:@"ab"] //returns true
[@"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</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Matching {
Line 2,108 ⟶ 3,405:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<syntaxhighlight lang="objc">[@"abcd" hasPrefix:@"ab"] //returns true
[@"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</syntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let match1 s1 s2 =
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)</langsyntaxhighlight>
 
testing in the top-level:
Line 2,126 ⟶ 3,430:
- : bool = true
 
<langsyntaxhighlight lang="ocaml">let match2 s1 s2 =
let len1 = String.length s1
and len2 = String.length s2 in
Line 2,135 ⟶ 3,439:
if (sub = s2) then true else aux (pred i)
in
aux (len1 - len2)</langsyntaxhighlight>
 
# match2 "It's raining, Hello World!" "umbrella" ;;
Line 2,142 ⟶ 3,446:
- : bool = true
 
<langsyntaxhighlight lang="ocaml">let match3 s1 s2 =
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)</langsyntaxhighlight>
 
# match3 "Hello World" "Hello" ;;
Line 2,154 ⟶ 3,458:
- : bool = true
 
<langsyntaxhighlight lang="ocaml">let match2_loc s1 s2 =
let len1 = String.length s1
and len2 = String.length s2 in
Line 2,163 ⟶ 3,467:
if (sub = s2) then (true, i) else aux (pred i)
in
aux (len1 - len2)</langsyntaxhighlight>
 
# match2_loc "The sun's shining, Hello World!" "raining" ;;
Line 2,170 ⟶ 3,474:
- : bool * int = (true, 10)
 
<langsyntaxhighlight lang="ocaml">let match2_num s1 s2 =
let len1 = String.length s1
and len2 = String.length s2 in
Line 2,181 ⟶ 3,485:
else aux (pred i) (n)
in
aux (len1 - len2) 0</langsyntaxhighlight>
 
# match2_num "This cloud looks like a camel, \
Line 2,189 ⟶ 3,493:
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}}==
 
<langsyntaxhighlight Oforthlang="oforth">: stringMatching(s1, s2)
| i |
s2 isAllAt(s1, 1) ifTrue: [ System.Out s1 << " begins with " << s2 << cr ]
Line 2,205 ⟶ 3,528:
System.Out s1 << " includes " << s2 << " at position : " << i << cr
i s2 size + ->i
] ;</langsyntaxhighlight>
 
{{out}}
Line 2,221 ⟶ 3,544:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
string s="sdfkjhgsdfkdfgkbopefioqwurti487sdfkrglkjfs9wrtgjglsdfkdkjcnmmb.,msfjflkjsdfk"
 
Line 2,257 ⟶ 3,580:
'
'Total matches: 5
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="parigp">startsWith(string, prefix)={
string=Vec(string);
prefix=Vec(prefix);
Line 2,287 ⟶ 3,610:
for(i=1,#suffix,if(prefix[i]!=string[i+#string-#suffix], return(0)));
1
};</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 2,293 ⟶ 3,616:
Using regexes:
 
<langsyntaxhighlight lang="perl">$str1 =~ /^\Q$str2\E/ # true if $str1 starts with $str2
$str1 =~ /\Q$str2\E/ # true if $str1 contains $str2
$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2</langsyntaxhighlight>
 
Using <code>index</code>:
 
<langsyntaxhighlight lang="perl">index($str1, $str2) == 0 # true if $str1 starts with $str2
index($str1, $str2) != -1 # true if $str1 contains $str2
rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2</langsyntaxhighlight>
 
Using <code>substr</code>:
 
<langsyntaxhighlight lang="perl">substr($str1, 0, length($str2)) eq $str2 # true if $str1 starts with $str2
substr($str1, - length($str2)) eq $str2 # true if $str1 ends with $str2</langsyntaxhighlight>
 
Bonus task ''(printing all positions where <code>$str2</code> appears in <code>$str1</code>)'':
 
<langsyntaxhighlight lang="perl">print $-[0], "\n" while $str1 =~ /\Q$str2\E/g; # using a regex</langsyntaxhighlight>
<langsyntaxhighlight lang="perl">my $i = -1; print $i, "\n" while ($i = index $str1, $str2, $i + 1) != -1; # using index</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
{{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>
"yes(1)"
"yes(2)"
"yes(3)"
"yes(4)"
1
16
33
{1,16,33}
</pre>
 
=={{header|Phixmonti}}==
Using string methods:
Simple solution
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/String_prepend
by Galileo, 11/2022 #/
 
include ..\Utilitys.pmt
<lang perl6>$haystack.starts-with($needle) # True if $haystack starts with $needle
$haystack.contains($needle) # True if $haystack contains $needle
$haystack.ends-with($needle) # True if $haystack ends with $needle</lang>
 
"the last thing the man said was the" "the" pstack
Using regexes:
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>
<lang perl6>so $haystack ~~ /^ $needle / # True if $haystack starts with $needle
More complex solution
so $haystack ~~ / $needle / # True if $haystack contains $needle
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/String_prepend
so $haystack ~~ / $needle $/ # True if $haystack ends with $needle</lang>
by Galileo, 11/2022 #/
 
include ..\Utilitys.pmt
Using <code>substr</code>:
 
"the last thing the man said was the" "the" pstack
<lang perl6>substr($haystack, 0, $needle.chars) eq $needle # True if $haystack starts with $needle
( ) rot rot >ps
substr($haystack, *-$needle.chars) eq $needle # True if $haystack ends with $needle</lang>
 
true while
Bonus task:
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
<lang perl6>$haystack.match($needle, :g)».from; # List of all positions where $needle appears in $haystack</lang>
 
len for get
=={{header|Phix}}==
dup 1 == if "Begins with keyword" ? drop else
<lang Phix>constant word = "the", -- (also try this with "th"/"he")
dup tps == if "Ends with keyword" ? drop else
sentence = "the last thing the man said was the"
"Locate at position " print ?
-- sentence = "thelastthingthemansaidwasthe" -- (practically the same results)
endif endif
 
endfor
-- A common, but potentially inefficient idiom for checking for a substring at the start is:
ps> drop
if match(word,sentence)=1 then
</syntaxhighlight>
?"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>
["the last thing the man said was the", "the"]
"yes(1)"
Begins with keyword
"yes(2)"
Locate at position 16
"yes(3)"
Ends with keyword
"yes(4)"
 
1
=== Press any key to exit ===</pre>
16
33
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
/**********************************************************************************
* This program gets needle and haystack from the caller (chm.html) (see below)
Line 2,436 ⟶ 3,797:
<p style="color: red";><strong><?php echo "$tx1" ?></strong></p>
</body>
</html></langsyntaxhighlight>
<langsyntaxhighlight lang="php"><?php
<!DOCTYPE html>
<!--
Line 2,477 ⟶ 3,838:
</form>
</body>
</html></langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight PicoLisplang="picolisp">: (pre? "ab" "abcd")
-> "abcd"
: (pre? "xy" "abcd")
Line 2,503 ⟶ 3,933:
 
: (positions "bc" "abcdabcd")
-> (2 6)</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Let s be one string, t be the other that might exist within s. */
/* 8-1-2011 */
Line 2,518 ⟶ 3,948:
 
if k > 0 then put skip edit (t, ' starts at position ', k) (a);
</syntaxhighlight>
</lang>
 
Optional extra:
 
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Handle multiple occurrences. */
n = 1;
Line 2,543 ⟶ 3,973:
else stop;
end;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
"spicywiener".StartsWith("spicy")
"spicywiener".Contains("icy")
"spicywiener".EndsWith("wiener")
"spicywiener".IndexOf("icy")
[regex]::Matches("spicywiener", "i").count
</syntaxhighlight>
{{out}}
<pre>
True
True
True
2
2
</pre>
 
=={{header|Prolog}}==
 
 
<syntaxhighlight lang="prolog">
:- system:set_prolog_flag(double_quotes,codes) .
 
:- [library(lists)] .
 
%! starts_with(FIRSTz,SECONDz)
%
% True if `SECONDz` is the beginning of `FIRSTz` .
 
starts_with(FIRSTz,SECONDz)
:-
lists:append(SECONDz,_,FIRSTz)
.
 
%! contains(FIRSTz,SECONDz)
%
% True once if `SECONDz` is contained within `FIRSTz` at one or more positions .
 
contains(FIRSTz,SECONDz)
:-
contains(FIRSTz,SECONDz,_) ,
!
.
 
%! contains(FIRSTz,SECONDz,NTH1)
%
% True if `SECONDz` is contained within `FIRSTz` at position `NTH1` .
 
contains(FIRSTz,SECONDz,NTH1)
:-
lists:append([PREFIXz,SECONDz,_SUFFIXz_],FIRSTz) ,
prolog:length(PREFIXz,NTH0) ,
NTH1 is NTH0 + 1
.
 
%! ends_with(FIRSTz,SECONDz)
%
% True if `SECONDz` is the ending of `FIRSTz` .
 
ends_with(FIRSTz,SECONDz)
:-
lists:append(_,SECONDz,FIRSTz)
.
 
</syntaxhighlight>
 
{{out}}
<pre>
 
?- starts_with("abcdef","abc") .
true .
 
?- starts_with("abc","abc") .
true .
 
?- starts_with("abc","abcd") .
false .
 
?- starts_with("dabc","abc") .
false .
 
?- starts_with("","") .
true .
 
?-
 
?- contains("abcdef","abc") .
true.
 
?- contains("abcdef","abc",NTH).
NTH = 1 ;
false.
 
?- contains("abcdef","de",NTH).
NTH = 4 ;
false.
 
?- contains("abcdef","f",NTH).
NTH = 6 ;
false.
 
?- contains("abcde","f",NTH).
false.
 
?- contains("","",NTH).
NTH = 1 ; % wtf ?
false.
 
?- contains("a","a",NTH).
NTH = 1 ; % wtf ?
false.
 
?-
 
?- ends_with("abc","abc") .
true ;
false .
 
?- ends_with("abc","bc") .
true ;
false .
 
?- ends_with("abcd","bc") .
false .
 
?- ends_with("","") .
true ;
false .
 
?-
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure StartsWith(String1$, String2$)
Protected Result
If FindString(String1$, String2$, 1) =1 ; E.g Found in possition 1
Line 2,560 ⟶ 4,122:
EndIf
ProcedureReturn Result
EndProcedure</langsyntaxhighlight>
And a verification
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
PrintN(Str(StartsWith("Rosettacode", "Rosetta"))) ; = 1
PrintN(Str(StartsWith("Rosettacode", "code"))) ; = 0
Line 2,572 ⟶ 4,134:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
An alternate and more complete solution:
<langsyntaxhighlight PureBasiclang="purebasic">Procedure startsWith(string1$, string2$)
;returns one if string1$ starts with string2$, otherwise returns zero
If FindString(string1$, string2$, 1) = 1
Line 2,616 ⟶ 4,178:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,629 ⟶ 4,191:
0
1</pre>
 
=={{header|PowerShell}}==
<lang Powershell>
"spicywiener".StartsWith("spicy")
"spicywiener".Contains("icy")
"spicywiener".EndsWith("wiener")
"spicywiener".IndexOf("icy")
[regex]::Matches("spicywiener", "i").count
</lang>
{{out}}
<pre>
True
True
True
2
2
</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">"abcd".startswith("ab") #returns True
"abcd".endswith("zn") #returns False
"bb" in "abab" #returns False
Line 2,654 ⟶ 4,199:
loc = "abab".find("bb") #returns -1
loc = "abab".find("ab") #returns 0
loc = "abab".find("ab",loc+1) #returns 2</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require srfi/13)
Line 2,664 ⟶ 4,268:
(string-contains "abab" "bb")
(string-contains "abab" "ba")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,673 ⟶ 4,277:
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
Using string methods:
 
<syntaxhighlight lang="raku" line>$haystack.starts-with($needle) # True if $haystack starts with $needle
$haystack.contains($needle) # True if $haystack contains $needle
$haystack.ends-with($needle) # True if $haystack ends with $needle</syntaxhighlight>
 
Using regexes:
 
<syntaxhighlight lang="raku" line>so $haystack ~~ /^ $needle / # True if $haystack starts with $needle
so $haystack ~~ / $needle / # True if $haystack contains $needle
so $haystack ~~ / $needle $/ # True if $haystack ends with $needle</syntaxhighlight>
 
Using <code>substr</code>:
 
<syntaxhighlight lang="raku" line>substr($haystack, 0, $needle.chars) eq $needle # True if $haystack starts with $needle
substr($haystack, *-$needle.chars) eq $needle # True if $haystack ends with $needle</syntaxhighlight>
 
Bonus task:
 
<syntaxhighlight lang="raku" line>$haystack.match($needle, :g)».from; # List of all positions where $needle appears in $haystack
$haystack.indices($needle :overlap); # Also find any overlapping instances of $needle in $haystack</syntaxhighlight>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">: startsWith? ( $1 $2 - f )
withLength &swap dip 0 swap ^strings'getSubset compare ;
 
Line 2,688 ⟶ 4,316:
 
"abcdefghijkl" "ijkl" endsWith?
"abcdefghijkl" "abc" endsWith?</langsyntaxhighlight>
 
=={{header|REXX}}==
Extra coding was added to take care of using plurals in the last output message.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates some basic character string testing (for matching). */
parse arg A B; LB=length(B) /*obtain A and B from the command line.*/
say 'string A = ' A A /*display string A to the terminal.*/
say 'string B = ' B B /* " " B " " " */
say copies('░', 70) /*display a line separator (fence). */
LB= length(B) /*get the length of string B in bytes*/
if left(A, LB)==B then say 'string A starts with string B'
else say "string A doesn't start with string B"
say /* [↓] another method using COMPARE BIF*/
p= pos(B, A)
/*╔══════════════════════════════════════════════════════════════════════════╗
║ if compare(A,B)==LB then say 'string A starts with string B' ║
║ else say "string A doesn't start with string B" ║
╚══════════════════════════════════════════════════════════════════════════╝*/
p=pos(B, A)
if p==0 then say "string A doesn't contain string B"
else say 'string A contains string B (starting in position' p")"
say
if right(A, LB)==bB then say 'string A ends with string B'
else say "string A doesn't end with string B"
say
$=; p= 0; do until p==0; p= pos(B, A, p+1)
if p\==0 then $= $',' p
end /*until*/
 
$=space(strip($, 'L', ",")) /*elide extra blanks and leading comma.*/
#$=words space( strip($) , 'L', ",") ) /*obtainelide numberextra ofblanks words in $and leading stringcomma.*/
#= words($) /*obtain number of words in $ string.*/
 
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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when the following is specified (the five Marx brothers): &nbsp; <tt> Chico_Harpo_Groucho_Zeppo_Gummo p </tt> }}
<pre>
Line 2,773 ⟶ 4,400:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aString = "Welcome to the Ring Programming Language"
bString = "Ring"
bStringIndex = substr(aString,bString)
if bStringIndex > 0 see "" + bStringIndex + " : " + bString ok
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="ruby">p 'abcd'.start_with?('ab') #returns true
p 'abcd'.end_with?('ab') #returns false
p 'abab'.include?('bb') #returns false
Line 2,790 ⟶ 4,436:
p 'abab'.index('ab') #returns 0
p 'abab'.index('ab', 1) #returns 2
p 'abab'.rindex('ab') #returns 2</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">s1$ = "abc def ghi klmnop"
s2$ = "abc" ' begins with
s3$ = "ef" ' is in the string
Line 2,820 ⟶ 4,466:
 
if mid$(s1$,len(s1$) + 1 - len(sn4$),len(sn4$)) <> sn4$ then a$ = "Not "
print "String:";s1$;" does ";a$;"end with:";sn4$</langsyntaxhighlight>
{{out}}
<pre>
Line 2,832 ⟶ 4,478:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn print_match(possible_match: Option<usize>) {
match possible_match {
Some(match_pos) => println!("Found match at pos {}", match_pos),
Line 2,853 ⟶ 4,499:
// Determining if the first string ends with the second string
assert!(s2.ends_with(s3));
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="rust">
fn main(){
let hello = String::from("Hello world");
Line 2,862 ⟶ 4,508:
hello.ends_with("ld"),
hello.contains("wi"));
}</langsyntaxhighlight>
 
{{out}}
Line 2,870 ⟶ 4,516:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">"abcd".startsWith("ab") //returns true
"abcd".endsWith("zn") //returns false
"abab".contains("bb") //returns false
Line 2,877 ⟶ 4,523:
var loc="abab".indexOf("bb") //returns -1
loc = "abab".indexOf("ab") //returns 0
loc = "abab".indexOf("ab", loc+1) //returns 2</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,895 ⟶ 4,560:
position := pos("abab", "ab", succ(position));
writeln(position); # position is 3
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,909 ⟶ 4,574:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var first = "abc-abcdef-abcd";
var second = "abc";
 
Line 2,923 ⟶ 4,588:
while (pos = first.index(second, pos+1) != -1) {
say "Match at pos: #{pos}";
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">a startsWith: b
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</lang> "inherited"
a indexOfString: b
a indexOfStringStartingAt: b
</syntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4"> s1 = 'abcdabefgab'
s2 = 'ab'
s3 = 'xy'
Line 2,946 ⟶ 4,615:
 
p3 OUTPUT = ?(s1 ? s2 RPOS(0)) "3. " s2 " ends " s1
END</langsyntaxhighlight>
{{out}}
<pre>1. ab begins abcdabefgab
Line 2,955 ⟶ 4,624:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">String.isPrefix "ab" "abcd"; (* returns true *)
String.isSuffix "zn" "abcd"; (* returns false *)
String.isSubstring "bb" "abab"; (* returns false *)
Line 2,961 ⟶ 4,630:
#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 *)</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">var str = "Hello, playground"
str.hasPrefix("Hell") //True
str.hasPrefix("hell") //False
Line 2,972 ⟶ 4,641:
 
str.hasSuffix("playground") //True
str.hasSuffix("world") //False</langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="tailspin">
templates find&{s:}
when <'$s;.*'> do '$; starts with $s;' !
when <'.*$s;'> do '$; ends with $s;' !
when <'.*$s;.*'> do '$; contains $s;' !
otherwise '$s; cannot be found in $;' !
end find
'abcd' -> find&{s:'ab'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'cd'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'bc'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'e'} -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
abcd starts with ab
abcd ends with cd
abcd contains bc
e cannot be found in abcd
</pre>
 
Working with composers and literal matchers to be able to handle any string.
<syntaxhighlight lang="tailspin">
composer startsWith&{s:}
@: 0;
(<='$s;'>? -> @:1; <'.*'>) $@
end startsWith
 
composer endsWith&{s:}
@: 0;
(<ends|'.*'>) $@
rule ends: (<'.'>* <='$s;'> -> @:1;)
end endsWith
 
composer contains&{s:}
@: 0;
(<~='$s;'>? <='$s;'>? -> @:1; <'.*'>) $@
end contains
 
templates find&{s:}
when <?($ -> startsWith&{s:$s} <=1>)> do '$; starts with $s;' !
when <?($ -> endsWith&{s:$s} <=1>)> do '$; ends with $s;' !
when <?($ -> contains&{s:$s} <=1>)> do '$; contains $s;' !
otherwise '$s; cannot be found in $;' !
end find
 
'abcd' -> find&{s:'ab'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'cd'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'bc'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'e'} -> !OUT::write
'
' -> !OUT::write
'banana' -> find&{s:'na'} -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
abcd starts with ab
abcd ends with cd
abcd contains bc
e cannot be found in abcd
banana ends with na
</pre>
 
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.
<syntaxhighlight lang="tailspin">
composer index&{s:}
@index: 0;
[<match>*]
rule match: ([<~='$s;'>? ...] -> @: $@ + 1 + $::length;) <'.'>? -> $@
end index
 
'ba is found in positions $:'banana' -> index&{s:'ba'}; in banana' -> !OUT::write
'
' -> !OUT::write
'ana is found in positions $:'banana' -> index&{s:'ana'}; in banana' -> !OUT::write
'
' -> !OUT::write
'c is found in positions $:'banana' -> index&{s:'c'}; in banana' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
ba is found in positions [1] in banana
ana is found in positions [2, 4] in banana
c is found in positions [] in banana
</pre>
 
=={{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>.
<langsyntaxhighlight lang="tcl">set isPrefix [string equal -length [string length $needle] $haystack $needle]
set isContained [expr {[string first $needle $haystack] >= 0}]
set isSuffix [string equal $needle [string range $haystack end-[expr {[string length $needle]-1}] end]]</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="tcl">set isPrefix [string match $needle* $haystack]
set isContained [string match *$needle* $haystack]
set isSuffix [string match *$needle $haystack]</langsyntaxhighlight>
 
Another powerful technique is to use the regular expression engine in literal string mode:
<langsyntaxhighlight lang="tcl">set isContained [regexp ***=$needle $haystack]</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="tcl">set matchLocations [regexp -indices -all -inline ***=$needle $haystack]
# 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 2,999 ⟶ 4,769:
foreach location $matchLocations {
puts "needle matched at index [lindex $location 0]"
}</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
ASK "string1", string1=""
Line 3,026 ⟶ 4,796:
PRINT string1," not ends with ",string2
ENDIF
</syntaxhighlight>
</lang>
{{out}}
<pre>string1 >Rosetta Code
Line 3,041 ⟶ 4,811:
===TXR Lisp===
 
<langsyntaxhighlight lang="txrlisp">(tree-case *args*
((big small)
(cond
Line 3,056 ⟶ 4,826:
(put-line `@small does not occur in @big`)))))
(otherwise
(put-line `usage: @(ldiff *full-args* *args*) <bigstring> <smallstring>`)))</langsyntaxhighlight>
{{out}}
<pre>$ txr cmatch2.tl x
Line 3,077 ⟶ 4,847:
===Pattern Language===
 
<langsyntaxhighlight lang="txr">@line
@(cases)
@ line
Line 3,102 ⟶ 4,872:
first line is not found in the second line
@ (end)
@(end)</langsyntaxhighlight>
 
{{out}}
Line 3,113 ⟶ 4,883:
0123
first line is a suffix of the second line</pre>
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">void main() {
var text = "一二三四五六七八九十";
var starts = "一二";
var ends = "九十";
var contains = "五六";
var not_contain = "百";
stdout.printf(@"text: $text\n\n", );
stdout.printf(@"starts with $starts: $(text.has_prefix(starts))\n");
stdout.printf(@"ends with $ends: $(text.has_suffix(ends))\n");
stdout.printf(@"starts with $starts: $(text.has_suffix(starts))\n");
stdout.printf(@"contains $contains: $(contains in text)\n");
stdout.printf(@"contains $not_contain: $(contains in text)\n");
}</syntaxhighlight>
 
{{out}}
 
<pre>
text: 一二三四五六七八九十
 
starts with 一二: true
ends with 九十: true
starts with 一二: false
contains 五六: true
contains 百: false
</pre>
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Public Sub string_matching()
word = "the" '-- (also try this with "th"/"he")
sentence = "the last thing the man said was the"
Line 3,145 ⟶ 4,943:
r = InStr(r + 1, sentence, word)
Loop
End Sub</langsyntaxhighlight>{{out}}
<pre>yes(1)
yes(2)
Line 3,153 ⟶ 4,951:
16
33 </pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Function StartsWith(s1,s2)
StartsWith = False
If Left(s1,Len(s2)) = s2 Then
Line 3,196 ⟶ 4,995:
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")</langsyntaxhighlight>
 
{{out}}
Line 3,209 ⟶ 5,008:
{{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}}==
<syntaxhighlight lang="wren">var s = "abracadabra"
var t = "abra"
var u = "ra"
var v = "cad"
System.print("'%(s)' starts with '%(t)' is %(s.startsWith(t))")
var indices = []
var start = 0
while (true) {
var ix = s.indexOf(u, start)
if (ix >= 0) {
indices.add(ix)
start = ix + u.count
if (start >= s.count) break
} else break
}
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))")</syntaxhighlight>
 
{{out}}
<pre>
'abracadabra' starts with 'abra' is true
'abracadabra' contains 'ra' is true at indices [2, 9]
'abracadabra' ends with 'cad' is false
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
 
Line 3,252 ⟶ 5,098:
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);
]</langsyntaxhighlight>
 
{{out}}
Line 3,264 ⟶ 5,110:
no
</pre>
 
=={{header|XProfan}}==
<syntaxhighlight lang="xprofan">
// XProfan can use StringParts, so the results here
// are the comma separated positions of the parts or 0
Proc Contains
Parameters string content, part
var string results = "0"
var long posi = 1
posi = InStr(part,content,posi)
if posi <> 0
results = str$(posi)
repeat
posi = InStr(part,content,posi+1)
case posi <> 0 : results = results + "," + str$(posi)
until posi == 0
endif
Return results
EndProc
 
Proc StartsWith
Parameters string content, part
Return if(Left$(content,Len(part)) == part, 1, 0)
EndProc
 
Proc EndsWith
Parameters string content, part
Return if(Right$(content,Len(part)) == part, 1, 0)
'Return if(Left$(content,Len(content)-Len(part)+1) == part, 1, 0)
EndProc
 
var string theContent = "foobar"
var string thePart = "foo"
Print "Starts with: "
Print " ("+thePart+" in "+theContent+") "+if(StartsWith(theContent,thePart),"Yes","No")
thePart = "back"
Print " ("+thePart+" in "+theContent+") "+if(StartsWith(theContent,thePart),"Yes","No")
 
theContent = "foooooobar"
Print "Contains: "
Print " ("+thePart+" in "+theContent+") "+ Contains(theContent,thePart)
thePart = "o"
Print " ("+thePart+" in "+theContent+") "+ Contains(theContent,thePart)
 
theContent = "foobar"
thePart = "back"
Print "Ends with: "
Print " ("+thePart+" in "+theContent+") "+if(EndsWith(theContent,thePart),"Yes","No")
thePart = "bar"
Print " ("+thePart+" in "+theContent+") "+if(EndsWith(theContent,thePart),"Yes","No")
 
waitkey
end</syntaxhighlight>
{{out}}
<pre>
Starts with:
(foo in foobar) Yes
(back in foobar) No
Contains:
(back in foooooobar) 0
(o in foooooobar) 2,3,4,5,6,7
Ends with:
(back in foobar) No
(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}}==
<langsyntaxhighlight lang="zkl">fcn f(text,p){ if(text.find(p)==0)println("Yep") else println("Nope") }
f("foobar","foo") //--> Yep
f("foobar","bar") //--> Nope</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn f(text,p){ if(Void!=(n:=text.find(p)))println("Contained @",n) else println("Nope") }
f("foobar","ob") //--> Contained @2
f("foobar","food") //--> Nope</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn f(text,p){
if( Void!=(n:=text.rfind(p)) and n+p.len()==text.len() )
println("tail gunner") else println("Nope")
Line 3,278 ⟶ 5,282:
f("foobar","r"); f("foobar","ar"); //--> tail gunners
f("foobar","ob"); //--> Nope
f("foobarfoobar","bar"); //--> tail gunner</langsyntaxhighlight>
 
{{omit from|bc|No string operations in bc}}
1,995

edits