String matching: Difference between revisions
Content added Content deleted
(→{{header|AWK}}: support part 2) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 23: | Line 23: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">print(‘abcd’.starts_with(‘ab’)) |
||
print(‘abcd’.ends_with(‘zn’)) |
print(‘abcd’.ends_with(‘zn’)) |
||
print(‘bb’ C ‘abab’) |
print(‘bb’ C ‘abab’) |
||
print(‘ab’ C ‘abab’) |
print(‘ab’ C ‘abab’) |
||
print(‘abab’.find(‘bb’) ? -1) |
print(‘abab’.find(‘bb’) ? -1) |
||
print(‘abab’.find(‘ab’) ? -1)</ |
print(‘abab’.find(‘ab’) ? -1)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 41: | Line 41: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm">* String matching 04/04/2017 |
||
STRMATCH CSECT |
STRMATCH CSECT |
||
USING STRMATCH,R15 |
USING STRMATCH,R15 |
||
Line 74: | Line 74: | ||
PG DC CL80' ' |
PG DC CL80' ' |
||
YREGS |
YREGS |
||
END STRMATCH</ |
END STRMATCH</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 88: | Line 88: | ||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program strMatching64.s */ |
/* program strMatching64.s */ |
||
Line 339: | Line 339: | ||
/* for this file see task include a file in language AArch64 assembly */ |
/* for this file see task include a file in language AArch64 assembly */ |
||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">BYTE FUNC FindS(CHAR ARRAY text,sub BYTE start) |
||
BYTE i,j,found |
BYTE i,j,found |
||
Line 450: | Line 450: | ||
TestEndsWith("1234abc","abc") |
TestEndsWith("1234abc","abc") |
||
TestEndsWith("1234abc","ab") |
TestEndsWith("1234abc","ab") |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_matching.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_matching.png Screenshot from Atari 8-bit computer] |
||
Line 466: | Line 466: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
<syntaxhighlight lang="ada"> |
|||
<lang Ada> |
|||
with Ada.Strings.Fixed; use Ada.Strings.Fixed; |
with Ada.Strings.Fixed; use Ada.Strings.Fixed; |
||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
Line 487: | Line 487: | ||
); |
); |
||
end Match_Strings; |
end Match_Strings; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 497: | Line 497: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">text t; |
||
data b; |
data b; |
||
Line 518: | Line 518: | ||
o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b.seek(t) == 0, |
o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b.seek(t) == 0, |
||
b.seek(t) != -1, |
b.seek(t) != -1, |
||
b.seek(t) != -1 && b.seek(t) + ~t == ~b);</ |
b.seek(t) != -1 && b.seek(t) + ~t == ~b);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>starts with, embeds, ends with "Bang": 1, 1, 0 |
<pre>starts with, embeds, ends with "Bang": 1, 1, 0 |
||
Line 529: | Line 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]}} |
{{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?}} |
{{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?}} |
||
< |
<syntaxhighlight lang="algol68"># define some appropriate OPerators # |
||
PRIO STARTSWITH = 5, ENDSWITH = 5; |
PRIO STARTSWITH = 5, ENDSWITH = 5; |
||
OP STARTSWITH = (STRING str, prefix)BOOL: # assuming LWB = 1 # |
OP STARTSWITH = (STRING str, prefix)BOOL: # assuming LWB = 1 # |
||
Line 546: | Line 546: | ||
(string in string("ab",loc,"abab")|loc|-1), # returns +1 # |
(string in string("ab",loc,"abab")|loc|-1), # returns +1 # |
||
(string in string("ab",loc2,"abab"[loc+1:])|loc+loc2|-1) # returns +3 # |
(string in string("ab",loc2,"abab"[loc+1:])|loc+loc2|-1) # returns +3 # |
||
))</ |
))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 553: | Line 553: | ||
=={{header|AppleScript}}== |
=={{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 string1 to "I felt happy" |
||
Line 569: | Line 569: | ||
-- Print the location of the match for part 2 |
-- Print the location of the match for part 2 |
||
offset of string2 in stringA --> 69</ |
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: |
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 |
on offset of needle in haystack |
||
local needle, haystack |
local needle, haystack |
||
Line 593: | Line 593: | ||
end offset |
end offset |
||
offset of "happy" in stringA --> {8, 44, 83, 110}</ |
offset of "happy" in stringA --> {8, 44, 83, 110}</syntaxhighlight> |
||
or, defining an '''offsets''' function in terms of a more general '''findIndices''': |
or, defining an '''offsets''' function in terms of a more general '''findIndices''': |
||
< |
<syntaxhighlight lang="applescript">-- offsets :: String -> String -> [Int] |
||
on offsets(needle, haystack) |
on offsets(needle, haystack) |
||
script match |
script match |
||
Line 666: | Line 666: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>{8, 44, 83, 110}</pre> |
<pre>{8, 44, 83, 110}</pre> |
||
Line 672: | Line 672: | ||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program strMatching.s */ |
/* program strMatching.s */ |
||
Line 914: | Line 914: | ||
bx lr @ return |
bx lr @ return |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">print prefix? "abcd" "ab" |
||
print prefix? "abcd" "cd" |
print prefix? "abcd" "cd" |
||
print suffix? "abcd" "ab" |
print suffix? "abcd" "ab" |
||
Line 929: | Line 929: | ||
print index "abcd" "bc" |
print index "abcd" "bc" |
||
print index "abcd" "xy"</ |
print index "abcd" "xy"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 945: | Line 945: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
<syntaxhighlight lang="autohotkey"> |
|||
<lang AutoHotkey> |
|||
String1 = abcd |
String1 = abcd |
||
String2 = abab |
String2 = abab |
||
Line 960: | Line 960: | ||
If TempVar = %String2% |
If TempVar = %String2% |
||
MsgBox, "%String1%" ends with "%String2%". |
MsgBox, "%String1%" ends with "%String2%". |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
< |
<syntaxhighlight lang="autoit">$string1 = "arduinoardblobard" |
||
$string2 = "ard" |
$string2 = "ard" |
||
Line 993: | Line 993: | ||
EndIf |
EndIf |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">#!/usr/bin/awk -f |
||
{ pos=index($2,$1) |
{ pos=index($2,$1) |
||
print $2, (pos==1 ? "begins" : "does not begin" ), "with " $1 |
print $2, (pos==1 ? "begins" : "does not begin" ), "with " $1 |
||
Line 1,013: | Line 1,013: | ||
print $2, (substr($2,pos)==$1 ? "ends" : "does not end"), "with " $1 |
print $2, (substr($2,pos)==$1 ? "ends" : "does not end"), "with " $1 |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|QBasic}} |
{{works with|QBasic}} |
||
< |
<syntaxhighlight lang="qbasic">first$ = "qwertyuiop" |
||
'Determining if the first string starts with second string |
'Determining if the first string starts with second string |
||
Line 1,045: | Line 1,045: | ||
END IF |
END IF |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,053: | Line 1,053: | ||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
< |
<syntaxhighlight lang="applesoftbasic">10 A$ = "THIS, THAT, AND THE OTHER THING" |
||
20 S$ = "TH" |
20 S$ = "TH" |
||
30 DEF FN S(P) = MID$(A$, P, LEN(S$)) = S$ |
30 DEF FN S(P) = MID$(A$, P, LEN(S$)) = S$ |
||
Line 1,070: | Line 1,070: | ||
310 E$(1) = "ENDS" |
310 E$(1) = "ENDS" |
||
320 E$(0) = "DOES NOT END" |
320 E$(0) = "DOES NOT END" |
||
330 PRINT E$(FN S(LEN(A$) - LEN(S$) + 1))" WITH "S$</ |
330 PRINT E$(FN S(LEN(A$) - LEN(S$) + 1))" WITH "S$</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight 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. |
::you put some of the CMD special characters (ex. %,!, etc) inside the strings. |
||
:: |
:: |
||
Line 1,142: | Line 1,142: | ||
set /a length+=1 |
set /a length+=1 |
||
goto loop |
goto loop |
||
::/The functions.</ |
::/The functions.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>"qwertyuiop" begins with "qwerty". |
<pre>"qwertyuiop" begins with "qwerty". |
||
Line 1,156: | Line 1,156: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> first$ = "The fox jumps over the dog" |
||
FOR test% = 1 TO 3 |
FOR test% = 1 TO 3 |
||
Line 1,188: | Line 1,188: | ||
UNTIL I% = 0 |
UNTIL I% = 0 |
||
= N% |
= N% |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>"The fox jumps over the dog" starts with "The" |
<pre>"The fox jumps over the dog" starts with "The" |
||
Line 1,202: | Line 1,202: | ||
<code>⍷</code> does much of the heavy lifting here. It is commuted with <code>˜</code> so the order of the arguments makes sense. |
<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 ← ∨´⍷˜ |
Contains ← ∨´⍷˜ |
||
Line 1,208: | Line 1,208: | ||
EW ← ¯1⊑⍷˜ |
EW ← ¯1⊑⍷˜ |
||
Locs ← /⍷˜</ |
Locs ← /⍷˜</syntaxhighlight> |
||
{{Out|Usage}} |
{{Out|Usage}} |
||
< |
<syntaxhighlight lang="bqn"> "abcd" SW "ab" |
||
1 |
1 |
||
"abcd" SW "cd" |
"abcd" SW "cd" |
||
Line 1,227: | Line 1,227: | ||
1 |
1 |
||
"abab" Locs "ab" |
"abab" Locs "ab" |
||
⟨ 0 2 ⟩</ |
⟨ 0 2 ⟩</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="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:I ?) & "sentence starts with 'I'" | "sentence does not start with 'I'") |
||
& out$(@(!sentence:? such ?) & "sentence contains 'such'" | "sentence does not contain 'such'") |
& out$(@(!sentence:? such ?) & "sentence contains 'such'" | "sentence does not contain 'such'") |
||
Line 1,239: | Line 1,239: | ||
| out$str$("sentence contains " !N " occurrences of 'be'") |
| out$str$("sentence contains " !N " occurrences of 'be'") |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
In the last line, Bracmat is forced by the always failing node <code>~</code> to backtrack until all occurrences of 'be' are found. |
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. |
Thereafter the pattern match expression fails. |
||
Line 1,253: | Line 1,253: | ||
=={{header|C}}== |
=={{header|C}}== |
||
Case sensitive matching: |
Case sensitive matching: |
||
< |
<syntaxhighlight lang="c">#include <string.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 1,284: | Line 1,284: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Starts with Test ( Hello,Hell ) : 1 |
<pre>Starts with Test ( Hello,Hell ) : 1 |
||
Line 1,290: | Line 1,290: | ||
Contains Test ( Google,msn ) : 0</pre> |
Contains Test ( Google,msn ) : 0</pre> |
||
Code without using string library to demonstrate how char strings are just pointers: |
Code without using string library to demonstrate how char strings are just pointers: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
/* returns 0 if no match, 1 if matched, -1 if matched and at end */ |
/* returns 0 if no match, 1 if matched, -1 if matched and at end */ |
||
Line 1,333: | Line 1,333: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>matching `A Short String' with `ort S': |
<pre>matching `A Short String' with `ort S': |
||
Line 1,350: | Line 1,350: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
{{works with|Mono|2.6}} |
{{works with|Mono|2.6}} |
||
< |
<syntaxhighlight lang="csharp"> |
||
class Program |
class Program |
||
{ |
{ |
||
Line 1,364: | Line 1,364: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <string> |
||
using namespace std; |
using namespace std; |
||
Line 1,380: | Line 1,380: | ||
s1.find(s2)//returns string::npos |
s1.find(s2)//returns string::npos |
||
int loc=s2.find(s3)//returns 0 |
int loc=s2.find(s3)//returns 0 |
||
loc=s2.find(s3,loc+1)//returns 2</ |
loc=s2.find(s3,loc+1)//returns 2</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="clojure">(def evals '((. "abcd" startsWith "ab") |
||
(. "abcd" endsWith "zn") |
(. "abcd" endsWith "zn") |
||
(. "abab" contains "bb") |
(. "abab" contains "bb") |
||
Line 1,393: | Line 1,393: | ||
user> (for [i evals] [i (eval i)]) |
user> (for [i evals] [i (eval i)]) |
||
([(. "abcd" startsWith "ab") true] [(. "abcd" endsWith "zn") false] [(. "abab" contains "bb") false] [(. "abab" contains "ab") true] [(. "abab" indexOf "bb") -1] [(let [loc (. "abab" indexOf "ab")] (. "abab" indexOf "ab" (dec loc))) 0])</ |
([(. "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])</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
Line 1,399: | Line 1,399: | ||
This example uses string slices, but a better implementation might use indexOf for slightly better performance. |
This example uses string slices, but a better implementation might use indexOf for slightly better performance. |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
matchAt = (s, frag, i) -> |
matchAt = (s, frag, i) -> |
||
s[i...i+frag.length] == frag |
s[i...i+frag.length] == frag |
||
Line 1,420: | Line 1,420: | ||
console.log matchLocations "bababab", "bab" # [0,2,4] |
console.log matchLocations "bababab", "bab" # [0,2,4] |
||
console.log matchLocations "xxx", "x" # [0,1,2] |
console.log matchLocations "xxx", "x" # [0,1,2] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun starts-with-p (str1 str2) |
(defun starts-with-p (str1 str2) |
||
"Determine whether `str1` starts with `str2`" |
"Determine whether `str1` starts with `str2`" |
||
Line 1,452: | Line 1,452: | ||
(print (containsp "ababaBa" "ba")) ; (1 3) |
(print (containsp "ababaBa" "ba")) ; (1 3) |
||
(print (containsp "foobar" "x")) ; NIL |
(print (containsp "foobar" "x")) ; NIL |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
BlackBox Component Builder |
BlackBox Component Builder |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE StringMatch; |
MODULE StringMatch; |
||
IMPORT StdLog,Strings; |
IMPORT StdLog,Strings; |
||
Line 1,570: | Line 1,570: | ||
END Do; |
END Do; |
||
END StringMatch. |
END StringMatch. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute: ^Q StringMatching.Do <br/> |
Execute: ^Q StringMatching.Do <br/> |
||
{{out}} |
{{out}} |
||
Line 1,595: | Line 1,595: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio; |
import std.stdio; |
||
import std.algorithm: startsWith, endsWith, find, countUntil; |
import std.algorithm: startsWith, endsWith, find, countUntil; |
||
Line 1,610: | Line 1,610: | ||
[1, 2, 3].countUntil(3).writeln; // 2 |
[1, 2, 3].countUntil(3).writeln; // 2 |
||
[1, 2, 3].countUntil([2, 3]).writeln; // 1 |
[1, 2, 3].countUntil([2, 3]).writeln; // 1 |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>true |
<pre>true |
||
Line 1,622: | Line 1,622: | ||
=={{header|DCL}}== |
=={{header|DCL}}== |
||
< |
<syntaxhighlight lang="dcl">$ first_string = p1 |
||
$ length_of_first_string = f$length( first_string ) |
$ length_of_first_string = f$length( first_string ) |
||
$ second_string = p2 |
$ second_string = p2 |
||
Line 1,645: | Line 1,645: | ||
$ else |
$ else |
||
$ write sys$output "first string does not end with the second string" |
$ write sys$output "first string does not end with the second string" |
||
$ endif</ |
$ endif</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ @string_matching efabcdef ef |
<pre>$ @string_matching efabcdef ef |
||
Line 1,665: | Line 1,665: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program CharacterMatching; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 1,677: | Line 1,677: | ||
Writeln(AnsiContainsText('abcd', 'ab')); // True |
Writeln(AnsiContainsText('abcd', 'ab')); // True |
||
WriteLn(Pos('ab', 'abcd')); // 1 |
WriteLn(Pos('ab', 'abcd')); // 1 |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang="dyalect">var value = "abcd".StartsWith("ab") |
||
value = "abcd".EndsWith("zn") //returns false |
value = "abcd".EndsWith("zn") //returns false |
||
value = "abab".Contains("bb") //returns false |
value = "abab".Contains("bb") //returns false |
||
value = "abab".Contains("ab") //returns true |
value = "abab".Contains("ab") //returns true |
||
var loc = "abab".IndexOf("bb") //returns -1 |
var loc = "abab".IndexOf("bb") //returns -1 |
||
loc = "abab".IndexOf("ab") //returns 0</ |
loc = "abab".IndexOf("ab") //returns 0</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def f(string1, string2) { |
||
println(string1.startsWith(string2)) |
println(string1.startsWith(string2)) |
||
Line 1,700: | Line 1,700: | ||
println(string1.endsWith(string2)) |
println(string1.endsWith(string2)) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(string-suffix? "nette" "Antoinette") → #t |
(string-suffix? "nette" "Antoinette") → #t |
||
(string-prefix? "Simon" "Simon & Garfunkel") → #t |
(string-prefix? "Simon" "Simon & Garfunkel") → #t |
||
Line 1,709: | Line 1,709: | ||
(string-match "Antoinette" "net") → #t ;; contains |
(string-match "Antoinette" "net") → #t ;; contains |
||
(string-index "net" "Antoinette") → 5 ;; substring location |
(string-index "net" "Antoinette") → 5 ;; substring location |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x : |
ELENA 4.x : |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
public program() |
public program() |
||
Line 1,736: | Line 1,736: | ||
console.readChar() |
console.readChar() |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
The String module has functions that cover the base requirements. |
The String module has functions that cover the base requirements. |
||
< |
<syntaxhighlight lang="elixir">s1 = "abcd" |
||
s2 = "adab" |
s2 = "adab" |
||
s3 = "ab" |
s3 = "ab" |
||
Line 1,767: | Line 1,767: | ||
Regex.scan(~r/#{s3}/, "abcabc", return: :index) |
Regex.scan(~r/#{s3}/, "abcabc", return: :index) |
||
# => [[{0, 2}], [{3, 2}]]</ |
# => [[{0, 2}], [{3, 2}]]</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun string-contains (needle haystack) |
||
(string-match (regexp-quote needle) haystack)) |
(string-match (regexp-quote needle) haystack)) |
||
Line 1,783: | Line 1,783: | ||
(string-prefix-p "after" "before center after") ;=> nil |
(string-prefix-p "after" "before center after") ;=> nil |
||
(string-contains "after" "before center after") ;=> 14 |
(string-contains "after" "before center after") ;=> 14 |
||
(string-suffix-p "after" "before center after") ;=> t</ |
(string-suffix-p "after" "before center after") ;=> t</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module(character_matching). |
-module(character_matching). |
||
-export([starts_with/2,ends_with/2,contains/2]). |
-export([starts_with/2,ends_with/2,contains/2]). |
||
Line 1,815: | Line 1,815: | ||
contains(_S1,_S2,_N,Acc) -> |
contains(_S1,_S2,_N,Acc) -> |
||
Acc. |
Acc. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">sequence first, second |
||
integer x |
integer x |
||
Line 1,847: | Line 1,847: | ||
else |
else |
||
printf(1, "'%s' does not end with '%s'\n", {first, second}) |
printf(1, "'%s' does not end with '%s'\n", {first, second}) |
||
end if</ |
end if</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,856: | Line 1,856: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">[<EntryPoint>] |
||
let main args = |
let main args = |
||
Line 1,879: | Line 1,879: | ||
if idx < 0 then None else Some (idx, idx+1)) 0 |
if idx < 0 then None else Some (idx, idx+1)) 0 |
||
|> Seq.iter (printfn "substring %A begins at position %d (zero-based)" contains) |
|> Seq.iter (printfn "substring %A begins at position %d (zero-based)" contains) |
||
0</ |
0</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>text = "一二三四五六七八九十" |
<pre>text = "一二三四五六七八九十" |
||
Line 1,895: | Line 1,895: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Does <code>cheesecake</code> start with <code>cheese</code>? |
Does <code>cheesecake</code> start with <code>cheese</code>? |
||
< |
<syntaxhighlight lang="factor">"cheesecake" "cheese" head? ! t</syntaxhighlight> |
||
Does <code>cheesecake</code> contain <code>sec</code> at any location? |
Does <code>cheesecake</code> contain <code>sec</code> at any location? |
||
< |
<syntaxhighlight lang="factor">"sec" "cheesecake" subseq? ! t</syntaxhighlight> |
||
Does <code>cheesecake</code> end with <code>cake</code>? |
Does <code>cheesecake</code> end with <code>cake</code>? |
||
< |
<syntaxhighlight lang="factor">"cheesecake" "cake" tail? ! t</syntaxhighlight> |
||
Where in <code>cheesecake</code> is the leftmost <code>sec</code>? |
Where in <code>cheesecake</code> is the leftmost <code>sec</code>? |
||
< |
<syntaxhighlight lang="factor">"sec" "cheesecake" subseq-start ! 4</syntaxhighlight> |
||
Where in <code>Mississippi</code> are all occurrences of <code>iss</code>? |
Where in <code>Mississippi</code> are all occurrences of <code>iss</code>? |
||
< |
<syntaxhighlight lang="factor">USE: regexp |
||
"Mississippi" "iss" <regexp> all-matching-slices [ from>> ] map ! { 1 4 }</ |
"Mississippi" "iss" <regexp> all-matching-slices [ from>> ] map ! { 1 4 }</syntaxhighlight> |
||
=={{header|Falcon}}== |
=={{header|Falcon}}== |
||
'''VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems falconic'' |
'''VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems falconic'' |
||
< |
<syntaxhighlight lang="falcon"> |
||
/* created by Aykayayciti Earl Lamont Montgomery |
/* created by Aykayayciti Earl Lamont Montgomery |
||
April 9th, 2018 */ |
April 9th, 2018 */ |
||
Line 1,923: | Line 1,923: | ||
> s1.endsWith(s2) ? @ "s1 ends with $s2" : @ "$s1 does not end with $s2" |
> s1.endsWith(s2) ? @ "s1 ends with $s2" : @ "$s1 does not end with $s2" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,944: | Line 1,944: | ||
* <code>indexrIgnoreCase</code> (like above, ignoring case for ASCII characters) |
* <code>indexrIgnoreCase</code> (like above, ignoring case for ASCII characters) |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 1,967: | Line 1,967: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,985: | Line 1,985: | ||
=={{header|FBSL}}== |
=={{header|FBSL}}== |
||
< |
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE |
||
DIM s = "roko, mat jane do" |
DIM s = "roko, mat jane do" |
||
Line 2,000: | Line 2,000: | ||
WHILE INSTR(mane, match, INSTR + 1): PRINT " ", INSTR;: WEND |
WHILE INSTR(mane, match, INSTR + 1): PRINT " ", INSTR;: WEND |
||
END SUB |
END SUB |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>"roko, mat jane do" starts with "roko" |
<pre>"roko, mat jane do" starts with "roko" |
||
Line 2,010: | Line 2,010: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: starts-with ( a l a2 l2 -- ? ) |
||
tuck 2>r min 2r> compare 0= ; |
tuck 2>r min 2r> compare 0= ; |
||
: ends-with ( a l a2 l2 -- ? ) |
: ends-with ( a l a2 l2 -- ? ) |
||
tuck 2>r negate over + 0 max /string 2r> compare 0= ; |
tuck 2>r negate over + 0 max /string 2r> compare 0= ; |
||
\ use SEARCH ( a l a2 l2 -- a3 l3 ? ) for contains</ |
\ use SEARCH ( a l a2 l2 -- a3 l3 ? ) for contains</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Line 2,023: | Line 2,023: | ||
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. |
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? |
SUBROUTINE STARTS(A,B) !Text A starts with text B? |
||
CHARACTER*(*) A,B |
CHARACTER*(*) A,B |
||
Line 2,064: | Line 2,064: | ||
CALL ENDS("Brief","Much longer") |
CALL ENDS("Brief","Much longer") |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: text strings are bounded by >''etc.''< in case of leading or trailing spaces. |
Output: text strings are bounded by >''etc.''< in case of leading or trailing spaces. |
||
<pre> |
<pre> |
||
Line 2,076: | Line 2,076: | ||
Similar program using modern Fortran style |
Similar program using modern Fortran style |
||
<syntaxhighlight lang="fortran"> |
|||
<lang Fortran> |
|||
!----------------------------------------------------------------------- |
!----------------------------------------------------------------------- |
||
!Main program string_matching |
!Main program string_matching |
||
Line 2,139: | Line 2,139: | ||
end function ends |
end function ends |
||
end program string_matching |
end program string_matching |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: false = 0, true = 1 ( + multiple occurrences if applicable) |
Output: false = 0, true = 1 ( + multiple occurrences if applicable) |
||
<pre> |
<pre> |
||
Line 2,154: | Line 2,154: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Dim As String s1 = "abracadabra" |
Dim As String s1 = "abracadabra" |
||
Line 2,179: | Line 2,179: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,193: | Line 2,193: | ||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=07bb32f4e8e8f7d81898cf41d4431a2e Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=07bb32f4e8e8f7d81898cf41d4431a2e Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim sString1 As String = "Hello world" |
Dim sString1 As String = "Hello world" |
||
Dim sString2 As String = "Hello" |
Dim sString2 As String = "Hello" |
||
Line 2,201: | Line 2,201: | ||
Print sString1 Ends Left(sString2, 5) 'Determine if the first string ends with the second string |
Print sString1 Ends Left(sString2, 5) 'Determine if the first string ends with the second string |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,212: | Line 2,212: | ||
{{trans|BASIC}} |
{{trans|BASIC}} |
||
< |
<syntaxhighlight lang="gml">#define charMatch |
||
{ |
{ |
||
first = "qwertyuiop"; |
first = "qwertyuiop"; |
||
Line 2,246: | Line 2,246: | ||
show_message("'" + first + "' does not end with '" + second + "'"); |
show_message("'" + first + "' does not end with '" + second + "'"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} (in message boxes, 1 per line): |
{{out}} (in message boxes, 1 per line): |
||
Line 2,255: | Line 2,255: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 2,284: | Line 2,284: | ||
func main() { |
func main() { |
||
match("abracadabra", "abr") |
match("abracadabra", "abr") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,297: | Line 2,297: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Examples: |
Examples: |
||
< |
<syntaxhighlight lang="groovy">assert "abcd".startsWith("ab") |
||
assert ! "abcd".startsWith("zn") |
assert ! "abcd".startsWith("zn") |
||
assert "abcd".endsWith("cd") |
assert "abcd".endsWith("cd") |
||
Line 2,319: | Line 2,319: | ||
assert indicesOf("abab", "ab") == [0, 2] |
assert indicesOf("abab", "ab") == [0, 2] |
||
assert indicesOf("abab", "ba") == [1] |
assert indicesOf("abab", "ba") == [1] |
||
assert indicesOf("abab", "xy") == []</ |
assert indicesOf("abab", "xy") == []</syntaxhighlight> |
||
All assertions pass, so there is no output. |
All assertions pass, so there is no output. |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">> import Data.List |
||
> "abc" `isPrefixOf` "abcdefg" |
> "abc" `isPrefixOf` "abcdefg" |
||
True |
True |
||
Line 2,335: | Line 2,335: | ||
> let infixes a b = findIndices (isPrefixOf a) $ tails b |
> let infixes a b = findIndices (isPrefixOf a) $ tails b |
||
> infixes "ab" "abcdefabqqab" |
> infixes "ab" "abcdefabqqab" |
||
[0,6,10]</ |
[0,6,10]</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
write("Matching s2 :=",image(s2 := "ab")," within s1:= ",image(s1 := "abcdabab")) |
write("Matching s2 :=",image(s2 := "ab")," within s1:= ",image(s1 := "abcdabab")) |
||
Line 2,347: | Line 2,347: | ||
write("Test #3 ending ", if s1[0-:*s2] == s2 then "matches" else "fails") |
write("Test #3 ending ", if s1[0-:*s2] == s2 then "matches" else "fails") |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,356: | Line 2,356: | ||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j">startswith=: ] -: ({.~ #) |
||
contains=: +./@:E.~ |
contains=: +./@:E.~ |
||
endswith=: ] -: ({.~ -@#)</ |
endswith=: ] -: ({.~ -@#)</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="j"> 'abcd' startswith 'ab' |
||
1 |
1 |
||
'abcd' startswith 'cd' |
'abcd' startswith 'cd' |
||
Line 2,379: | Line 2,379: | ||
1 |
1 |
||
'abab' I.@E.~ 'ab' NB. find starting indicies |
'abab' I.@E.~ 'ab' NB. find starting indicies |
||
0 2</ |
0 2</syntaxhighlight> |
||
Note that these verbs contain no constraints restricting them to sequences of characters and so also apply to arrays of type other than character: |
Note that these verbs contain no constraints restricting them to sequences of characters and so also apply to arrays of type other than character: |
||
< |
<syntaxhighlight lang="j"> 0 1 2 3 startswith 0 1 NB. integer |
||
1 |
1 |
||
4.2 5.1 1.3 9 3 contains 1.3 4.2 NB. floating point |
4.2 5.1 1.3 9 3 contains 1.3 4.2 NB. floating point |
||
0 |
0 |
||
4.2 5.1 1.3 4.2 9 3 contains 1.3 4.2 |
4.2 5.1 1.3 4.2 9 3 contains 1.3 4.2 |
||
1</ |
1</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">"abcd".startsWith("ab") //returns true |
||
"abcd".endsWith("zn") //returns false |
"abcd".endsWith("zn") //returns false |
||
"abab".contains("bb") //returns false |
"abab".contains("bb") //returns false |
||
Line 2,396: | Line 2,396: | ||
int loc = "abab".indexOf("bb") //returns -1 |
int loc = "abab".indexOf("bb") //returns -1 |
||
loc = "abab".indexOf("ab") //returns 0 |
loc = "abab".indexOf("ab") //returns 0 |
||
loc = "abab".indexOf("ab",loc+1) //returns 2</ |
loc = "abab".indexOf("ab",loc+1) //returns 2</syntaxhighlight> |
||
// -----------------------------------------------------------// |
// -----------------------------------------------------------// |
||
Line 2,438: | Line 2,438: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">var stringA = "tacoloco" |
||
, stringB = "co" |
, stringB = "co" |
||
, q1, q2, q2multi, m |
, q1, q2, q2multi, m |
||
Line 2,464: | Line 2,464: | ||
console.log(" In fact, it happens "+q2matches.length+" times within '"+stringA+"', at index"+(q2matches.length > 1 ? "es" : "")+" "+q2matches.join(', ')+".") |
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."))</ |
console.log("3: Does '"+stringA+"' end with '"+stringB+"'? " + ( q3 ? "Yes." : "No."))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,474: | Line 2,474: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
Using the builtins of jq 1.4 and later: |
Using the builtins of jq 1.4 and later: |
||
< |
<syntaxhighlight lang="jq"># startswith/1 is boolean: |
||
"abc" | startswith("ab") |
"abc" | startswith("ab") |
||
#=> true</ |
#=> true</syntaxhighlight> |
||
< |
<syntaxhighlight lang="jq"># index/1 returns the index or null, |
||
# so the jq test "if index(_) then ...." can be used |
# so the jq test "if index(_) then ...." can be used |
||
# without any type conversion. |
# without any type conversion. |
||
"abcd" | index( "bc") |
"abcd" | index( "bc") |
||
#=> 1</ |
#=> 1</syntaxhighlight> |
||
< |
<syntaxhighlight lang="jq"># endswith/1 is also boolean: |
||
"abc" | endswith("bc") |
"abc" | endswith("bc") |
||
#=> true</ |
#=> true</syntaxhighlight> |
||
Using the regex functions available in jq 1.5: |
Using the regex functions available in jq 1.5: |
||
< |
<syntaxhighlight lang="jq">"abc" | test( "^ab") |
||
"abcd" | test("bc") |
"abcd" | test("bc") |
||
"abcd" | test("cd$")</ |
"abcd" | test("cd$")</syntaxhighlight> |
||
===Multiple Occurrences=== |
===Multiple Occurrences=== |
||
To determine all the indices of one string in another: |
To determine all the indices of one string in another: |
||
< |
<syntaxhighlight lang="sh"># In jq 1.4 or later: |
||
jq -n '"abcdabcd" | indices("bc")' |
jq -n '"abcdabcd" | indices("bc")' |
||
[ |
[ |
||
1, |
1, |
||
5 |
5 |
||
]</ |
]</syntaxhighlight> |
||
In jq 1.5, the regex function match/1 can also be used: |
In jq 1.5, the regex function match/1 can also be used: |
||
< |
<syntaxhighlight lang="sh">$ jq -n '"abcdabcd" | match("bc"; "g") | .offset' |
||
1 |
1 |
||
5</ |
5</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia"> |
||
startswith("abcd","ab") #returns true |
startswith("abcd","ab") #returns true |
||
findfirst("ab", "abcd") #returns 1:2, indices range where string was found |
findfirst("ab", "abcd") #returns 1:2, indices range where string was found |
||
Line 2,519: | Line 2,519: | ||
println(r.offset) |
println(r.offset) |
||
end #returns 1, then 3 matching the two starting indices where the substring was found |
end #returns 1, then 3 matching the two starting indices where the substring was found |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k">startswith: {:[0<#p:_ss[x;y];~*p;0]} |
||
endswith: {0=(-#y)+(#x)-*_ss[x;y]} |
endswith: {0=(-#y)+(#x)-*_ss[x;y]} |
||
contains: {0<#_ss[x;y]}</ |
contains: {0<#_ss[x;y]}</syntaxhighlight> |
||
'''Example:''' |
'''Example:''' |
||
< |
<syntaxhighlight lang="k"> startswith["abcd";"ab"] |
||
1 |
1 |
||
startswith["abcd";"bc"] |
startswith["abcd";"bc"] |
||
Line 2,541: | Line 2,541: | ||
0 |
0 |
||
_ss["abcdabceabc";"abc"] / location of matches |
_ss["abcdabceabc";"abc"] / location of matches |
||
0 4 8</ |
0 4 8</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 2,555: | Line 2,555: | ||
if (b) println(" at locations ${s1.indexOf(s2) + 1} and ${s1.lastIndexOf(s2) + 1}") |
if (b) println(" at locations ${s1.indexOf(s2) + 1} and ${s1.lastIndexOf(s2) + 1}") |
||
else println() |
else println() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,565: | Line 2,565: | ||
=={{header|Ksh}}== |
=={{header|Ksh}}== |
||
< |
<syntaxhighlight lang="ksh"> |
||
#!/bin/ksh |
#!/bin/ksh |
||
exec 2> /tmp/String_matching.err |
exec 2> /tmp/String_matching.err |
||
Line 2,634: | Line 2,634: | ||
unset posarr ; typeset -a posarr |
unset posarr ; typeset -a posarr |
||
done |
done |
||
done</ |
done</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
Hello Starts with Hell |
Hello Starts with Hell |
||
Line 2,684: | Line 2,684: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
|||
<lang Scheme> |
|||
{def S.in |
{def S.in |
||
{def S.in.r {lambda {:c :w :i :n} |
{def S.in.r {lambda {:c :w :i :n} |
||
Line 2,729: | Line 2,729: | ||
-> -1 // is not in |
-> -1 // is not in |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">: 2array 2 compress ; : bi* '_ set dip _ execute ; : bi@ dup bi* ; |
||
: comb "" split ; : concat "" join ; : dip swap '_ set execute _ ; |
: comb "" split ; : concat "" join ; : dip swap '_ set execute _ ; |
||
: first 0 extract swap drop ; : flip comb reverse concat ; |
: first 0 extract swap drop ; : flip comb reverse concat ; |
||
Line 2,751: | Line 2,751: | ||
"rosettacode" "ocat" contains . # 0 |
"rosettacode" "ocat" contains . # 0 |
||
"rosettacode" "edoc" end-with . # 0 |
"rosettacode" "edoc" end-with . # 0 |
||
"rosettacode" "code" contains . # 7</ |
"rosettacode" "code" contains . # 7</syntaxhighlight> |
||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">local( |
||
a = 'a quick brown peanut jumped over a quick brown fox', |
a = 'a quick brown peanut jumped over a quick brown fox', |
||
b = 'a quick brown' |
b = 'a quick brown' |
||
Line 2,768: | Line 2,768: | ||
//Determining if the first string ends with the second string |
//Determining if the first string ends with the second string |
||
#a->endswith(#b) // false</ |
#a->endswith(#b) // false</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">'1---Determining if the first string starts with second string |
||
st1$="first string" |
st1$="first string" |
||
st2$="first" |
st2$="first" |
||
Line 2,801: | Line 2,801: | ||
print "First string ends with second string." |
print "First string ends with second string." |
||
end if |
end if |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">a = "Hello world!" |
||
b = "Hello" |
b = "Hello" |
||
Line 2,825: | Line 2,825: | ||
-- Print the location of the match for part 2 |
-- Print the location of the match for part 2 |
||
put offset(b, a) |
put offset(b, a) |
||
-- 7</ |
-- 7</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to starts.with? :sub :thing |
||
if empty? :sub [output "true] |
if empty? :sub [output "true] |
||
if empty? :thing [output "false] |
if empty? :thing [output "false] |
||
Line 2,844: | Line 2,844: | ||
show starts.with? "dog "doghouse ; true |
show starts.with? "dog "doghouse ; true |
||
show ends.with? "house "doghouse ; true |
show ends.with? "house "doghouse ; true |
||
show substring? "gho "doghouse ; true (built-in)</ |
show substring? "gho "doghouse ; true (built-in)</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">s1 = "string" |
||
s2 = "str" |
s2 = "str" |
||
s3 = "ing" |
s3 = "ing" |
||
Line 2,859: | Line 2,859: | ||
print( "s1 ends with s2: ", select( 2, string.find( s1, s2 ) ) == string.len( s1 ) ) |
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 ) )</ |
print( "s1 ends with s3: ", select( 2, string.find( s1, s3 ) ) == string.len( s1 ) )</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module StringMatch { |
Module StringMatch { |
||
A$="Hello World" |
A$="Hello World" |
||
Line 2,878: | Line 2,878: | ||
} |
} |
||
StringMatch |
StringMatch |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,891: | Line 2,891: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
These facilities are all to be found in the StringTools package in 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 |
> with( StringTools ): # bind package exports at the top-level |
||
> s := "dzrIemaWWIMidXYZwGiqkOOn": |
> s := "dzrIemaWWIMidXYZwGiqkOOn": |
||
Line 2,923: | Line 2,923: | ||
> {seq}( s[ i .. i + 2 ], i = p ); # check them |
> {seq}( s[ i .. i + 2 ], i = p ); # check them |
||
{"XYZ"} |
{"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. |
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}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">StartWith[x_, y_] := MemberQ[Flatten[StringPosition[x, y]], 1] |
||
EndWith[x_, y_] := MemberQ[Flatten[StringPosition[x, y]], StringLength[x]] |
EndWith[x_, y_] := MemberQ[Flatten[StringPosition[x, y]], StringLength[x]] |
||
StartWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"] |
StartWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"] |
||
EndWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"] |
EndWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"] |
||
StringPosition["XYZaaabXYZaaaaXYZXYZ", "XYZ"]</ |
StringPosition["XYZaaabXYZaaaaXYZXYZ", "XYZ"]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>True |
<pre>True |
||
Line 2,938: | Line 2,938: | ||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
<syntaxhighlight lang="matlab"> |
|||
<lang Matlab> |
|||
% 1. Determining if the first string starts with second string |
% 1. Determining if the first string starts with second string |
||
strcmp(str1,str2,length(str2)) |
strcmp(str1,str2,length(str2)) |
||
Line 2,950: | Line 2,950: | ||
% 2. Handle multiple occurrences of a string for part 2. |
% 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 |
ix = strfind(s1,s2); % ix is a vector containing the starting positions of s2 within s1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|min}}== |
=={{header|min}}== |
||
One way might be: |
One way might be: |
||
{{works with|min|0.19.6}} |
{{works with|min|0.19.6}} |
||
< |
<syntaxhighlight lang="min">(indexof 0 ==) :starts-with? |
||
(indexof -1 !=) :contains? |
(indexof -1 !=) :contains? |
||
((/ $/) swap 1 insert "" join regex ("") !=) :ends-with? |
((/ $/) swap 1 insert "" join regex ("") !=) :ends-with? |
||
Line 2,961: | Line 2,961: | ||
"minimalistic" "min" starts-with? puts! |
"minimalistic" "min" starts-with? puts! |
||
"minimalistic" "list" contains? puts! |
"minimalistic" "list" contains? puts! |
||
"minimalistic" "list" ends-with? puts!</ |
"minimalistic" "list" ends-with? puts!</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,972: | Line 2,972: | ||
We first extend the built-in string class with three new methods, and then demonstrate their use on some sample strings. |
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 |
return self.len >= s.len and s[:s.len] == s |
||
end function |
end function |
||
Line 3,011: | Line 3,011: | ||
print |
print |
||
print firstQ + doesOrNot[first.endsWith(second)] + "end with " + secondQ</ |
print firstQ + doesOrNot[first.endsWith(second)] + "end with " + secondQ</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,030: | Line 3,030: | ||
* Otherwise, <tt>$a0</tt> contains <tt>$a1</tt> starting at the specified location. |
* 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. |
* 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 |
;input: $a0 = ptr to string 1 |
||
; $a1 = ptr to string 2 |
; $a1 = ptr to string 2 |
||
Line 3,066: | Line 3,066: | ||
addiu sp,sp,4 |
addiu sp,sp,4 |
||
jr ra |
jr ra |
||
nop</ |
nop</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="mips">main: |
||
la $a0,MyString |
la $a0,MyString |
||
la $a1,Test1 ;this code was recompiled 5 times, testing a different string each time. |
la $a1,Test1 ;this code was recompiled 5 times, testing a different string each time. |
||
Line 3,109: | Line 3,109: | ||
.ascii "1",0 ;InString returned 0x1A (decimal 26) |
.ascii "1",0 ;InString returned 0x1A (decimal 26) |
||
.byte 0 |
.byte 0 |
||
.align 4</ |
.align 4</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols |
options replace format comments java crossref savelog symbols |
||
Line 3,160: | Line 3,160: | ||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
---- |
---- |
||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">(setq str "abcdefbcghi") |
||
;; test if str starts with "ab" |
;; test if str starts with "ab" |
||
Line 3,182: | Line 3,182: | ||
(push idx pos -1)))) |
(push idx pos -1)))) |
||
(find-all-pos "bc" str)</ |
(find-all-pos "bc" str)</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import strutils |
||
let s = "The quick brown fox" |
let s = "The quick brown fox" |
||
Line 3,199: | Line 3,199: | ||
let pos = find(s, " brown ") # -1 if not found. |
let pos = find(s, " brown ") # -1 if not found. |
||
if pos >= 0: |
if pos >= 0: |
||
echo "“ brown ” is located at position: " & $pos</ |
echo "“ brown ” is located at position: " & $pos</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,208: | Line 3,208: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class Matching { |
class Matching { |
||
Line 3,222: | Line 3,222: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
< |
<syntaxhighlight lang="objc">[@"abcd" hasPrefix:@"ab"] //returns true |
||
[@"abcd" hasSuffix:@"zn"] //returns false |
[@"abcd" hasSuffix:@"zn"] //returns false |
||
int loc = [@"abab" rangeOfString:@"bb"].location //returns -1 |
int loc = [@"abab" rangeOfString:@"bb"].location //returns -1 |
||
loc = [@"abab" rangeOfString:@"ab"].location //returns 0 |
loc = [@"abab" rangeOfString:@"ab"].location //returns 0 |
||
loc = [@"abab" rangeOfString:@"ab" options:0 range:NSMakeRange(loc+1, [@"abab" length]-(loc+1))].location //returns 2</ |
loc = [@"abab" rangeOfString:@"ab" options:0 range:NSMakeRange(loc+1, [@"abab" length]-(loc+1))].location //returns 2</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let match1 s1 s2 = |
||
let len1 = String.length s1 |
let len1 = String.length s1 |
||
and len2 = String.length s2 in |
and len2 = String.length s2 in |
||
if len1 < len2 then false else |
if len1 < len2 then false else |
||
let sub = String.sub s1 0 len2 in |
let sub = String.sub s1 0 len2 in |
||
(sub = s2)</ |
(sub = s2)</syntaxhighlight> |
||
testing in the top-level: |
testing in the top-level: |
||
Line 3,247: | Line 3,247: | ||
- : bool = true |
- : bool = true |
||
< |
<syntaxhighlight lang="ocaml">let match2 s1 s2 = |
||
let len1 = String.length s1 |
let len1 = String.length s1 |
||
and len2 = String.length s2 in |
and len2 = String.length s2 in |
||
Line 3,256: | Line 3,256: | ||
if (sub = s2) then true else aux (pred i) |
if (sub = s2) then true else aux (pred i) |
||
in |
in |
||
aux (len1 - len2)</ |
aux (len1 - len2)</syntaxhighlight> |
||
# match2 "It's raining, Hello World!" "umbrella" ;; |
# match2 "It's raining, Hello World!" "umbrella" ;; |
||
Line 3,263: | Line 3,263: | ||
- : bool = true |
- : bool = true |
||
< |
<syntaxhighlight lang="ocaml">let match3 s1 s2 = |
||
let len1 = String.length s1 |
let len1 = String.length s1 |
||
and len2 = String.length s2 in |
and len2 = String.length s2 in |
||
if len1 < len2 then false else |
if len1 < len2 then false else |
||
let sub = String.sub s1 (len1 - len2) len2 in |
let sub = String.sub s1 (len1 - len2) len2 in |
||
(sub = s2)</ |
(sub = s2)</syntaxhighlight> |
||
# match3 "Hello World" "Hello" ;; |
# match3 "Hello World" "Hello" ;; |
||
Line 3,275: | Line 3,275: | ||
- : bool = true |
- : bool = true |
||
< |
<syntaxhighlight lang="ocaml">let match2_loc s1 s2 = |
||
let len1 = String.length s1 |
let len1 = String.length s1 |
||
and len2 = String.length s2 in |
and len2 = String.length s2 in |
||
Line 3,284: | Line 3,284: | ||
if (sub = s2) then (true, i) else aux (pred i) |
if (sub = s2) then (true, i) else aux (pred i) |
||
in |
in |
||
aux (len1 - len2)</ |
aux (len1 - len2)</syntaxhighlight> |
||
# match2_loc "The sun's shining, Hello World!" "raining" ;; |
# match2_loc "The sun's shining, Hello World!" "raining" ;; |
||
Line 3,291: | Line 3,291: | ||
- : bool * int = (true, 10) |
- : bool * int = (true, 10) |
||
< |
<syntaxhighlight lang="ocaml">let match2_num s1 s2 = |
||
let len1 = String.length s1 |
let len1 = String.length s1 |
||
and len2 = String.length s2 in |
and len2 = String.length s2 in |
||
Line 3,302: | Line 3,302: | ||
else aux (pred i) (n) |
else aux (pred i) (n) |
||
in |
in |
||
aux (len1 - len2) 0</ |
aux (len1 - len2) 0</syntaxhighlight> |
||
# match2_num "This cloud looks like a camel, \ |
# match2_num "This cloud looks like a camel, \ |
||
Line 3,313: | Line 3,313: | ||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: stringMatching(s1, s2) |
||
| i | |
| i | |
||
s2 isAllAt(s1, 1) ifTrue: [ System.Out s1 << " begins with " << s2 << cr ] |
s2 isAllAt(s1, 1) ifTrue: [ System.Out s1 << " begins with " << s2 << cr ] |
||
Line 3,326: | Line 3,326: | ||
System.Out s1 << " includes " << s2 << " at position : " << i << cr |
System.Out s1 << " includes " << s2 << " at position : " << i << cr |
||
i s2 size + ->i |
i s2 size + ->i |
||
] ;</ |
] ;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,342: | Line 3,342: | ||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
string s="sdfkjhgsdfkdfgkbopefioqwurti487sdfkrglkjfs9wrtgjglsdfkdkjcnmmb.,msfjflkjsdfk" |
string s="sdfkjhgsdfkdfgkbopefioqwurti487sdfkrglkjfs9wrtgjglsdfkdkjcnmmb.,msfjflkjsdfk" |
||
Line 3,378: | Line 3,378: | ||
' |
' |
||
'Total matches: 5 |
'Total matches: 5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PARI/GP}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="parigp">startsWith(string, prefix)={ |
||
string=Vec(string); |
string=Vec(string); |
||
prefix=Vec(prefix); |
prefix=Vec(prefix); |
||
Line 3,408: | Line 3,408: | ||
for(i=1,#suffix,if(prefix[i]!=string[i+#string-#suffix], return(0))); |
for(i=1,#suffix,if(prefix[i]!=string[i+#string-#suffix], return(0))); |
||
1 |
1 |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Line 3,414: | Line 3,414: | ||
Using regexes: |
Using regexes: |
||
< |
<syntaxhighlight 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 contains $str2 |
||
$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2</ |
$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2</syntaxhighlight> |
||
Using <code>index</code>: |
Using <code>index</code>: |
||
< |
<syntaxhighlight lang="perl">index($str1, $str2) == 0 # true if $str1 starts with $str2 |
||
index($str1, $str2) != -1 # true if $str1 contains $str2 |
index($str1, $str2) != -1 # true if $str1 contains $str2 |
||
rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2</ |
rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2</syntaxhighlight> |
||
Using <code>substr</code>: |
Using <code>substr</code>: |
||
< |
<syntaxhighlight 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</ |
substr($str1, - length($str2)) eq $str2 # true if $str1 ends with $str2</syntaxhighlight> |
||
Bonus task ''(printing all positions where <code>$str2</code> appears in <code>$str1</code>)'': |
Bonus task ''(printing all positions where <code>$str2</code> appears in <code>$str1</code>)'': |
||
< |
<syntaxhighlight lang="perl">print $-[0], "\n" while $str1 =~ /\Q$str2\E/g; # using a regex</syntaxhighlight> |
||
< |
<syntaxhighlight lang="perl">my $i = -1; print $i, "\n" while ($i = index $str1, $str2, $i + 1) != -1; # using index</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
{{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: #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: #000000;">sentence</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"the last thing the man said was the"</span> |
||
Line 3,468: | Line 3,468: | ||
<span style="color: #000080;font-style:italic;">-- or equivalently:</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> |
<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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,482: | Line 3,482: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
/********************************************************************************** |
/********************************************************************************** |
||
* This program gets needle and haystack from the caller (chm.html) (see below) |
* This program gets needle and haystack from the caller (chm.html) (see below) |
||
Line 3,540: | Line 3,540: | ||
<p style="color: red";><strong><?php echo "$tx1" ?></strong></p> |
<p style="color: red";><strong><?php echo "$tx1" ?></strong></p> |
||
</body> |
</body> |
||
</html></ |
</html></syntaxhighlight> |
||
< |
<syntaxhighlight lang="php"><?php |
||
<!DOCTYPE html> |
<!DOCTYPE html> |
||
<!-- |
<!-- |
||
Line 3,581: | Line 3,581: | ||
</form> |
</form> |
||
</body> |
</body> |
||
</html></ |
</html></syntaxhighlight> |
||
=={{header|Picat}}== |
=={{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>. |
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 => |
go => |
||
Line 3,639: | Line 3,639: | ||
All2 = findall([Start9,End9], find(S7," ",Start9,End9)), |
All2 = findall([Start9,End9], find(S7," ",Start9,End9)), |
||
println(positions=All2), |
println(positions=All2), |
||
nl.</ |
nl.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,653: | Line 3,653: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">: (pre? "ab" "abcd") |
||
-> "abcd" |
-> "abcd" |
||
: (pre? "xy" "abcd") |
: (pre? "xy" "abcd") |
||
Line 3,676: | Line 3,676: | ||
: (positions "bc" "abcdabcd") |
: (positions "bc" "abcdabcd") |
||
-> (2 6)</ |
-> (2 6)</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
/* Let s be one string, t be the other that might exist within s. */ |
/* Let s be one string, t be the other that might exist within s. */ |
||
/* 8-1-2011 */ |
/* 8-1-2011 */ |
||
Line 3,691: | Line 3,691: | ||
if k > 0 then put skip edit (t, ' starts at position ', k) (a); |
if k > 0 then put skip edit (t, ' starts at position ', k) (a); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Optional extra: |
Optional extra: |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
/* Handle multiple occurrences. */ |
/* Handle multiple occurrences. */ |
||
n = 1; |
n = 1; |
||
Line 3,716: | Line 3,716: | ||
else stop; |
else stop; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang Powershell> |
|||
"spicywiener".StartsWith("spicy") |
"spicywiener".StartsWith("spicy") |
||
"spicywiener".Contains("icy") |
"spicywiener".Contains("icy") |
||
Line 3,725: | Line 3,725: | ||
"spicywiener".IndexOf("icy") |
"spicywiener".IndexOf("icy") |
||
[regex]::Matches("spicywiener", "i").count |
[regex]::Matches("spicywiener", "i").count |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,738: | Line 3,738: | ||
< |
<syntaxhighlight lang="prolog"> |
||
:- system:set_prolog_flag(double_quotes,codes) . |
:- system:set_prolog_flag(double_quotes,codes) . |
||
Line 3,782: | Line 3,782: | ||
. |
. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,851: | Line 3,851: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure StartsWith(String1$, String2$) |
||
Protected Result |
Protected Result |
||
If FindString(String1$, String2$, 1) =1 ; E.g Found in possition 1 |
If FindString(String1$, String2$, 1) =1 ; E.g Found in possition 1 |
||
Line 3,865: | Line 3,865: | ||
EndIf |
EndIf |
||
ProcedureReturn Result |
ProcedureReturn Result |
||
EndProcedure</ |
EndProcedure</syntaxhighlight> |
||
And a verification |
And a verification |
||
< |
<syntaxhighlight lang="purebasic">If OpenConsole() |
||
PrintN(Str(StartsWith("Rosettacode", "Rosetta"))) ; = 1 |
PrintN(Str(StartsWith("Rosettacode", "Rosetta"))) ; = 1 |
||
PrintN(Str(StartsWith("Rosettacode", "code"))) ; = 0 |
PrintN(Str(StartsWith("Rosettacode", "code"))) ; = 0 |
||
Line 3,877: | Line 3,877: | ||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
An alternate and more complete solution: |
An alternate and more complete solution: |
||
< |
<syntaxhighlight lang="purebasic">Procedure startsWith(string1$, string2$) |
||
;returns one if string1$ starts with string2$, otherwise returns zero |
;returns one if string1$ starts with string2$, otherwise returns zero |
||
If FindString(string1$, string2$, 1) = 1 |
If FindString(string1$, string2$, 1) = 1 |
||
Line 3,921: | Line 3,921: | ||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 |
<pre>1 |
||
Line 3,936: | Line 3,936: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">"abcd".startswith("ab") #returns True |
||
"abcd".endswith("zn") #returns False |
"abcd".endswith("zn") #returns False |
||
"bb" in "abab" #returns False |
"bb" in "abab" #returns False |
||
Line 3,942: | Line 3,942: | ||
loc = "abab".find("bb") #returns -1 |
loc = "abab".find("bb") #returns -1 |
||
loc = "abab".find("ab") #returns 0 |
loc = "abab".find("ab") #returns 0 |
||
loc = "abab".find("ab",loc+1) #returns 2</ |
loc = "abab".find("ab",loc+1) #returns 2</syntaxhighlight> |
||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
<syntaxhighlight lang="qb64"> |
|||
<lang QB64> |
|||
DefStr S |
DefStr S |
||
DefInt P |
DefInt P |
||
Line 3,964: | Line 3,964: | ||
Wend |
Wend |
||
Print string2; " is present "; pcount; " times into "; string1 |
Print string2; " is present "; pcount; " times into "; string1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
These work for any nests (i.e. dynamic arrays), not just strings (i.e. nests of chars). |
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 ) |
[ tuck size negate split nip = ] is ends ( [ [ --> b ) |
||
Line 3,991: | Line 3,991: | ||
$ "abcdefgh" $ "xyz" ends echobool cr |
$ "abcdefgh" $ "xyz" ends echobool cr |
||
$ "abcdefgh" $ "cde" contains echobool cr |
$ "abcdefgh" $ "cde" contains echobool cr |
||
$ "abcdefgh" $ "xyz" contains echobool cr</ |
$ "abcdefgh" $ "xyz" contains echobool cr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,004: | Line 4,004: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require srfi/13) |
(require srfi/13) |
||
Line 4,011: | Line 4,011: | ||
(string-contains "abab" "bb") |
(string-contains "abab" "bb") |
||
(string-contains "abab" "ba") |
(string-contains "abab" "ba") |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,025: | Line 4,025: | ||
Using string methods: |
Using string methods: |
||
<lang |
<syntaxhighlight lang="raku" line>$haystack.starts-with($needle) # True if $haystack starts with $needle |
||
$haystack.contains($needle) # True if $haystack contains $needle |
$haystack.contains($needle) # True if $haystack contains $needle |
||
$haystack.ends-with($needle) # True if $haystack ends with $needle</ |
$haystack.ends-with($needle) # True if $haystack ends with $needle</syntaxhighlight> |
||
Using regexes: |
Using regexes: |
||
<lang |
<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 contains $needle |
||
so $haystack ~~ / $needle $/ # True if $haystack ends with $needle</ |
so $haystack ~~ / $needle $/ # True if $haystack ends with $needle</syntaxhighlight> |
||
Using <code>substr</code>: |
Using <code>substr</code>: |
||
<lang |
<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</ |
substr($haystack, *-$needle.chars) eq $needle # True if $haystack ends with $needle</syntaxhighlight> |
||
Bonus task: |
Bonus task: |
||
<lang |
<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</ |
$haystack.indices($needle :overlap); # Also find any overlapping instances of $needle in $haystack</syntaxhighlight> |
||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">: startsWith? ( $1 $2 - f ) |
||
withLength &swap dip 0 swap ^strings'getSubset compare ; |
withLength &swap dip 0 swap ^strings'getSubset compare ; |
||
Line 4,059: | Line 4,059: | ||
"abcdefghijkl" "ijkl" endsWith? |
"abcdefghijkl" "ijkl" endsWith? |
||
"abcdefghijkl" "abc" endsWith?</ |
"abcdefghijkl" "abc" endsWith?</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Extra coding was added to take care of using plurals in the last output message. |
Extra coding was added to take care of using plurals in the last output message. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates some basic character string testing (for matching). */ |
||
parse arg A B /*obtain A and B from the command line.*/ |
parse arg A B /*obtain A and B from the command line.*/ |
||
say 'string A = ' A /*display string A to the terminal.*/ |
say 'string A = ' A /*display string A to the terminal.*/ |
||
Line 4,088: | Line 4,088: | ||
if #==0 then say "string A doesn't contain string B" |
if #==0 then say "string A doesn't contain string B" |
||
else say 'string A contains string B ' # " time"left('s', #>1), |
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. */</ |
"(at position"left('s', #>1) $")" /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
{{out|output|text= when the following is specified (the five Marx brothers): <tt> Chico_Harpo_Groucho_Zeppo_Gummo p </tt> }} |
{{out|output|text= when the following is specified (the five Marx brothers): <tt> Chico_Harpo_Groucho_Zeppo_Gummo p </tt> }} |
||
<pre> |
<pre> |
||
Line 4,143: | Line 4,143: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
aString = "Welcome to the Ring Programming Language" |
aString = "Welcome to the Ring Programming Language" |
||
bString = "Ring" |
bString = "Ring" |
||
bStringIndex = substr(aString,bString) |
bStringIndex = substr(aString,bString) |
||
if bStringIndex > 0 see "" + bStringIndex + " : " + bString ok |
if bStringIndex > 0 see "" + bStringIndex + " : " + bString ok |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">p 'abcd'.start_with?('ab') #returns true |
||
p 'abcd'.end_with?('ab') #returns false |
p 'abcd'.end_with?('ab') #returns false |
||
p 'abab'.include?('bb') #returns false |
p 'abab'.include?('bb') #returns false |
||
Line 4,160: | Line 4,160: | ||
p 'abab'.index('ab') #returns 0 |
p 'abab'.index('ab') #returns 0 |
||
p 'abab'.index('ab', 1) #returns 2 |
p 'abab'.index('ab', 1) #returns 2 |
||
p 'abab'.rindex('ab') #returns 2</ |
p 'abab'.rindex('ab') #returns 2</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">s1$ = "abc def ghi klmnop" |
||
s2$ = "abc" ' begins with |
s2$ = "abc" ' begins with |
||
s3$ = "ef" ' is in the string |
s3$ = "ef" ' is in the string |
||
Line 4,190: | Line 4,190: | ||
if mid$(s1$,len(s1$) + 1 - len(sn4$),len(sn4$)) <> sn4$ then a$ = "Not " |
if mid$(s1$,len(s1$) + 1 - len(sn4$),len(sn4$)) <> sn4$ then a$ = "Not " |
||
print "String:";s1$;" does ";a$;"end with:";sn4$</ |
print "String:";s1$;" does ";a$;"end with:";sn4$</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,202: | Line 4,202: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn print_match(possible_match: Option<usize>) { |
||
match possible_match { |
match possible_match { |
||
Some(match_pos) => println!("Found match at pos {}", match_pos), |
Some(match_pos) => println!("Found match at pos {}", match_pos), |
||
Line 4,223: | Line 4,223: | ||
// Determining if the first string ends with the second string |
// Determining if the first string ends with the second string |
||
assert!(s2.ends_with(s3)); |
assert!(s2.ends_with(s3)); |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="rust"> |
||
fn main(){ |
fn main(){ |
||
let hello = String::from("Hello world"); |
let hello = String::from("Hello world"); |
||
Line 4,232: | Line 4,232: | ||
hello.ends_with("ld"), |
hello.ends_with("ld"), |
||
hello.contains("wi")); |
hello.contains("wi")); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,240: | Line 4,240: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">"abcd".startsWith("ab") //returns true |
||
"abcd".endsWith("zn") //returns false |
"abcd".endsWith("zn") //returns false |
||
"abab".contains("bb") //returns false |
"abab".contains("bb") //returns false |
||
Line 4,247: | Line 4,247: | ||
var loc="abab".indexOf("bb") //returns -1 |
var loc="abab".indexOf("bb") //returns -1 |
||
loc = "abab".indexOf("ab") //returns 0 |
loc = "abab".indexOf("ab") //returns 0 |
||
loc = "abab".indexOf("ab", loc+1) //returns 2</ |
loc = "abab".indexOf("ab", loc+1) //returns 2</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 4,265: | Line 4,265: | ||
position := pos("abab", "ab", succ(position)); |
position := pos("abab", "ab", succ(position)); |
||
writeln(position); # position is 3 |
writeln(position); # position is 3 |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,279: | Line 4,279: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var first = "abc-abcdef-abcd"; |
||
var second = "abc"; |
var second = "abc"; |
||
Line 4,293: | Line 4,293: | ||
while (pos = first.index(second, pos+1) != -1) { |
while (pos = first.index(second, pos+1) != -1) { |
||
say "Match at pos: #{pos}"; |
say "Match at pos: #{pos}"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">a startsWith: b |
||
a includesSubCollection: b. "inherited from superclass" |
a includesSubCollection: b. "inherited from superclass" |
||
a includesString: b. "the same, but more readable" |
a includesString: b. "the same, but more readable" |
||
Line 4,304: | Line 4,304: | ||
a indexOfString: b |
a indexOfString: b |
||
a indexOfStringStartingAt: b |
a indexOfStringStartingAt: b |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang="snobol4"> s1 = 'abcdabefgab' |
||
s2 = 'ab' |
s2 = 'ab' |
||
s3 = 'xy' |
s3 = 'xy' |
||
Line 4,320: | Line 4,320: | ||
p3 OUTPUT = ?(s1 ? s2 RPOS(0)) "3. " s2 " ends " s1 |
p3 OUTPUT = ?(s1 ? s2 RPOS(0)) "3. " s2 " ends " s1 |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1. ab begins abcdabefgab |
<pre>1. ab begins abcdabefgab |
||
Line 4,329: | Line 4,329: | ||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">String.isPrefix "ab" "abcd"; (* returns true *) |
||
String.isSuffix "zn" "abcd"; (* returns false *) |
String.isSuffix "zn" "abcd"; (* returns false *) |
||
String.isSubstring "bb" "abab"; (* returns false *) |
String.isSubstring "bb" "abab"; (* returns false *) |
||
Line 4,335: | Line 4,335: | ||
#2 (Substring.base (#2 (Substring.position "bb" (Substring.full "abab")))); (* returns 4 *) |
#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.full "abab")))); (* returns 0 *) |
||
val loc' = #2 (Substring.base (#2 (Substring.position "ab" (Substring.extract ("abab", loc+1, NONE))))); (* returns 2 *)</ |
val loc' = #2 (Substring.base (#2 (Substring.position "ab" (Substring.extract ("abab", loc+1, NONE))))); (* returns 2 *)</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">var str = "Hello, playground" |
||
str.hasPrefix("Hell") //True |
str.hasPrefix("Hell") //True |
||
str.hasPrefix("hell") //False |
str.hasPrefix("hell") //False |
||
Line 4,346: | Line 4,346: | ||
str.hasSuffix("playground") //True |
str.hasSuffix("playground") //True |
||
str.hasSuffix("world") //False</ |
str.hasSuffix("world") //False</syntaxhighlight> |
||
=={{header|Tailspin}}== |
=={{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. |
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:} |
templates find&{s:} |
||
when <'$s;.*'> do '$; starts with $s;' ! |
when <'$s;.*'> do '$; starts with $s;' ! |
||
Line 4,368: | Line 4,368: | ||
' -> !OUT::write |
' -> !OUT::write |
||
'abcd' -> find&{s:'e'} -> !OUT::write |
'abcd' -> find&{s:'e'} -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,378: | Line 4,378: | ||
Working with composers and literal matchers to be able to handle any string. |
Working with composers and literal matchers to be able to handle any string. |
||
< |
<syntaxhighlight lang="tailspin"> |
||
composer startsWith&{s:} |
composer startsWith&{s:} |
||
@: 0; |
@: 0; |
||
Line 4,415: | Line 4,415: | ||
' -> !OUT::write |
' -> !OUT::write |
||
'banana' -> find&{s:'na'} -> !OUT::write |
'banana' -> find&{s:'na'} -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,427: | Line 4,427: | ||
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). |
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. |
This has also been crafted to work with strings containing special regex characters by using literal equality. |
||
< |
<syntaxhighlight lang="tailspin"> |
||
composer index&{s:} |
composer index&{s:} |
||
@index: 0; |
@index: 0; |
||
Line 4,441: | Line 4,441: | ||
' -> !OUT::write |
' -> !OUT::write |
||
'c is found in positions $:'banana' -> index&{s:'c'}; in banana' -> !OUT::write |
'c is found in positions $:'banana' -> index&{s:'c'}; in banana' -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,451: | Line 4,451: | ||
=={{header|Tcl}}== |
=={{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>. |
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>. |
||
< |
<syntaxhighlight lang="tcl">set isPrefix [string equal -length [string length $needle] $haystack $needle] |
||
set isContained [expr {[string first $needle $haystack] >= 0}] |
set isContained [expr {[string first $needle $haystack] >= 0}] |
||
set isSuffix [string equal $needle [string range $haystack end-[expr {[string length $needle]-1}] end]]</ |
set isSuffix [string equal $needle [string range $haystack end-[expr {[string length $needle]-1}] end]]</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="tcl">set isPrefix [string match $needle* $haystack] |
||
set isContained [string match *$needle* $haystack] |
set isContained [string match *$needle* $haystack] |
||
set isSuffix [string match *$needle $haystack]</ |
set isSuffix [string match *$needle $haystack]</syntaxhighlight> |
||
Another powerful technique is to use the regular expression engine in literal string mode: |
Another powerful technique is to use the regular expression engine in literal string mode: |
||
< |
<syntaxhighlight lang="tcl">set isContained [regexp ***=$needle $haystack]</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight 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 |
# 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 |
# to match and the index where the needle finished matching |
||
Line 4,474: | Line 4,474: | ||
foreach location $matchLocations { |
foreach location $matchLocations { |
||
puts "needle matched at index [lindex $location 0]" |
puts "needle matched at index [lindex $location 0]" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
ASK "string1", string1="" |
ASK "string1", string1="" |
||
Line 4,501: | Line 4,501: | ||
PRINT string1," not ends with ",string2 |
PRINT string1," not ends with ",string2 |
||
ENDIF |
ENDIF |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>string1 >Rosetta Code |
<pre>string1 >Rosetta Code |
||
Line 4,516: | Line 4,516: | ||
===TXR Lisp=== |
===TXR Lisp=== |
||
< |
<syntaxhighlight lang="txrlisp">(tree-case *args* |
||
((big small) |
((big small) |
||
(cond |
(cond |
||
Line 4,531: | Line 4,531: | ||
(put-line `@small does not occur in @big`))))) |
(put-line `@small does not occur in @big`))))) |
||
(otherwise |
(otherwise |
||
(put-line `usage: @(ldiff *full-args* *args*) <bigstring> <smallstring>`)))</ |
(put-line `usage: @(ldiff *full-args* *args*) <bigstring> <smallstring>`)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ txr cmatch2.tl x |
<pre>$ txr cmatch2.tl x |
||
Line 4,552: | Line 4,552: | ||
===Pattern Language=== |
===Pattern Language=== |
||
< |
<syntaxhighlight lang="txr">@line |
||
@(cases) |
@(cases) |
||
@ line |
@ line |
||
Line 4,577: | Line 4,577: | ||
first line is not found in the second line |
first line is not found in the second line |
||
@ (end) |
@ (end) |
||
@(end)</ |
@(end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,590: | Line 4,590: | ||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala">void main() { |
||
var text = "一二三四五六七八九十"; |
var text = "一二三四五六七八九十"; |
||
var starts = "一二"; |
var starts = "一二"; |
||
Line 4,603: | Line 4,603: | ||
stdout.printf(@"contains $contains: $(contains in text)\n"); |
stdout.printf(@"contains $contains: $(contains in text)\n"); |
||
stdout.printf(@"contains $not_contain: $(contains in text)\n"); |
stdout.printf(@"contains $not_contain: $(contains in text)\n"); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,618: | Line 4,618: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
{{trans|Phix}}< |
{{trans|Phix}}<syntaxhighlight lang="vb">Public Sub string_matching() |
||
word = "the" '-- (also try this with "th"/"he") |
word = "the" '-- (also try this with "th"/"he") |
||
sentence = "the last thing the man said was the" |
sentence = "the last thing the man said was the" |
||
Line 4,648: | Line 4,648: | ||
r = InStr(r + 1, sentence, word) |
r = InStr(r + 1, sentence, word) |
||
Loop |
Loop |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>yes(1) |
<pre>yes(1) |
||
yes(2) |
yes(2) |
||
Line 4,658: | Line 4,658: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">Function StartsWith(s1,s2) |
||
StartsWith = False |
StartsWith = False |
||
If Left(s1,Len(s2)) = s2 Then |
If Left(s1,Len(s2)) = s2 Then |
||
Line 4,700: | Line 4,700: | ||
WScript.StdOut.Write "Contains test, 'o' in 'fooooobar': " & Contains("fooooobar","o") |
WScript.StdOut.Write "Contains test, 'o' in 'fooooobar': " & Contains("fooooobar","o") |
||
WScript.StdOut.WriteLine |
WScript.StdOut.WriteLine |
||
WScript.StdOut.Write "Ends with test, 'bar' in 'foobar': " & EndsWith("foobar","bar")</ |
WScript.StdOut.Write "Ends with test, 'bar' in 'foobar': " & EndsWith("foobar","bar")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,716: | Line 4,716: | ||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
{{trans|Delphi}} |
{{trans|Delphi}} |
||
< |
<syntaxhighlight lang="vlang">fn main() { |
||
str := 'abcd' |
str := 'abcd' |
||
println(str.starts_with('ab')) // True |
println(str.starts_with('ab')) // True |
||
Line 4,723: | Line 4,723: | ||
println(str.contains('ab')) // True |
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 |
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}} |
{{out}} |
||
Line 4,735: | Line 4,735: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="ecmascript">var s = "abracadabra" |
||
var t = "abra" |
var t = "abra" |
||
var u = "ra" |
var u = "ra" |
||
Line 4,752: | Line 4,752: | ||
var contained = indices.count > 0 |
var contained = indices.count > 0 |
||
System.print("'%(s)' contains '%(u)' is %(contained) %(contained ? "at indices %(indices)" : "")") |
System.print("'%(s)' contains '%(u)' is %(contained) %(contained ? "at indices %(indices)" : "")") |
||
System.print("'%(s)' ends with '%(v)' is %(s.endsWith(v))")</ |
System.print("'%(s)' ends with '%(v)' is %(s.endsWith(v))")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,762: | Line 4,762: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
string 0; \use zero-terminated strings |
string 0; \use zero-terminated strings |
||
Line 4,803: | Line 4,803: | ||
Text(0, if StrFind(Str, "with") = StrLen(Str)-StrLen("with") then "yes" else "no"); CrLf(0); \3. |
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); |
Text(0, if StrFind(Str, "x w" ) = StrLen(Str)-StrLen("x w" ) then "yes" else "no"); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,817: | Line 4,817: | ||
=={{header|XProfan}}== |
=={{header|XProfan}}== |
||
<syntaxhighlight lang="xprofan"> |
|||
<lang XProfan> |
|||
// XProfan can use StringParts, so the results here |
// XProfan can use StringParts, so the results here |
||
// are the comma separated positions of the parts or 0 |
// are the comma separated positions of the parts or 0 |
||
Line 4,867: | Line 4,867: | ||
waitkey |
waitkey |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,883: | Line 4,883: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
<syntaxhighlight lang="yabasic"> |
|||
<lang Yabasic> |
|||
cadena1$ = "qwertyuiop" |
cadena1$ = "qwertyuiop" |
||
Line 4,912: | Line 4,912: | ||
end if |
end if |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,923: | Line 4,923: | ||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |
||
{{trans|MIPS Assembly}} |
{{trans|MIPS Assembly}} |
||
< |
<syntaxhighlight lang="z80">InString: |
||
;input: hl = pointer to string 1 |
;input: hl = pointer to string 1 |
||
; de = pointer to string 2 |
; de = pointer to string 2 |
||
Line 4,952: | Line 4,952: | ||
InString_overhead: |
InString_overhead: |
||
inc hl |
inc hl |
||
jr InString_again</ |
jr InString_again</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="z80">org &1000 |
||
ld hl,TestString |
ld hl,TestString |
||
ld de,Test1 ;recompiled with each test string and tested it |
ld de,Test1 ;recompiled with each test string and tested it |
||
Line 4,972: | Line 4,972: | ||
db "efg",0 ;returns 4 |
db "efg",0 ;returns 4 |
||
Test4: |
Test4: |
||
db "z",0 ;returns 7</ |
db "z",0 ;returns 7</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn f(text,p){ if(text.find(p)==0)println("Yep") else println("Nope") } |
||
f("foobar","foo") //--> Yep |
f("foobar","foo") //--> Yep |
||
f("foobar","bar") //--> Nope</ |
f("foobar","bar") //--> Nope</syntaxhighlight> |
||
< |
<syntaxhighlight 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","ob") //--> Contained @2 |
||
f("foobar","food") //--> Nope</ |
f("foobar","food") //--> Nope</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">fcn f(text,p){ |
||
if( Void!=(n:=text.rfind(p)) and n+p.len()==text.len() ) |
if( Void!=(n:=text.rfind(p)) and n+p.len()==text.len() ) |
||
println("tail gunner") else println("Nope") |
println("tail gunner") else println("Nope") |
||
Line 4,987: | Line 4,987: | ||
f("foobar","r"); f("foobar","ar"); //--> tail gunners |
f("foobar","r"); f("foobar","ar"); //--> tail gunners |
||
f("foobar","ob"); //--> Nope |
f("foobar","ob"); //--> Nope |
||
f("foobarfoobar","bar"); //--> tail gunner</ |
f("foobarfoobar","bar"); //--> tail gunner</syntaxhighlight> |
||
{{omit from|bc|No string operations in bc}} |
{{omit from|bc|No string operations in bc}} |