Substring: Difference between revisions

10,975 bytes added ,  16 days ago
Add Ecstasy example
No edit summary
(Add Ecstasy example)
 
(33 intermediate revisions by 14 users not shown)
Line 29:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V s = ‘abcdefgh’
V n = 2
V m = 3
Line 38:
print(s[0 .< (len)-1]) // whole string minus last character
print(s[s.index(char) .+ m]) // starting from a known character char="d" within the string and of m length
print(s[s.index(chars) .+ m]) // starting from a known substring chars="cd" within the string and of m length</langsyntaxhighlight>
 
{{out}}
Line 51:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program subString64.s */
Line 342:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 353:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC FindC(CHAR ARRAY text CHAR c)
BYTE i
 
Line 425:
PrintF("Substring start from '%S' and len %B: ""%S""%E%E",sub,m,res)
FI
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Substring.png Screenshot from Atari 8-bit computer]
Line 450:
=={{header|Ada}}==
String in [[Ada]] is an array of Character elements indexed by Positive:
<langsyntaxhighlight Adalang="ada">type String is array (Positive range <>) of Character;</langsyntaxhighlight>
Substring is a first-class object in [[Ada]], an anonymous subtype of String. The language uses the term '''slice''' for it. Slices can be retrieved, assigned and passed as a parameter to subprograms in mutable or immutable mode. A slice is specified as:
<langsyntaxhighlight Adalang="ada">A (<first-index>..<last-index>)</langsyntaxhighlight>
 
A string array in [[Ada]] can start with any positive index. This is why the implementation below uses Str'First in all slices, which in this concrete case is 1, but intentionally left in the code because the task refers to N as an ''offset'' to the string beginning rather than an ''index'' in the string. In [[Ada]] it is unusual to deal with slices in such way. One uses plain string index instead.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
 
Line 468:
Put_Line (Head (Tail (Str, Str'Last - Index (Str, "d", 1)), M));
Put_Line (Head (Tail (Str, Str'Last - Index (Str, "de", 1) - 1), M));
end Test_Slices;</langsyntaxhighlight>
{{out}}
<pre>
Line 483:
Shifting strings left or right removes characters from the ends.
 
<langsyntaxhighlight lang="aikido">
const str = "abcdefg"
var n = 2
Line 496:
var s = find (str, "bc")
println (str[s, s+m-1]) // pos of bc length 3
</syntaxhighlight>
</lang>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">text s;
data b, d;
 
Line 516:
b_cast(d, "brown");
o_text(cut(s, b_find(b, d), 15));
o_newline();</langsyntaxhighlight>
{{out}}
<pre>quick brown fox
Line 532:
 
<!-- {{works 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.fc9.i386]}} -->
<langsyntaxhighlight Algol68lang="algol68">main: (
STRING s = "abcdefgh";
INT n = 2, m = 3;
Line 547:
string in string("de", pos, s);
printf(($gl$, s[pos:pos+m-1]))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 559:
=={{header|Apex}}==
In Apex, the substring method returns a new String that begins with the character at the specified zero-based startIndex and extends to the end of the String.
<langsyntaxhighlight lang="apex">String x = 'testing123';
//Test1: testing123
System.debug('Test1: ' + x.substring(0,x.length()));
Line 574:
//Test7: e
System.debug('Test7: ' + x.substring(1,2));
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
Line 583:
(Functional primitives version)
{{trans|Haskell}}
<langsyntaxhighlight AppleScriptlang="applescript">-- SUBSTRINGS -----------------------------------------------------------------
 
-- take :: Int -> Text -> Text
Line 685:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre>from n in, of n length 五六七
Line 695:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 1,007:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">str: "abcdefgh"
n: 2
m: 3
Line 1,029:
; starting from a known substring chars="cd"
; within the string and of m length
print slice str index str "cd" m+(index str "cd")-1</langsyntaxhighlight>
 
{{out}}
Line 1,041:
=={{header|AutoHotkey}}==
The code contains some alternatives.
<langsyntaxhighlight lang="autohotkey">String := "abcdefghijklmnopqrstuvwxyz"
; also: String = abcdefghijklmnopqrstuvwxyz
n := 12
Line 1,075:
; StringMid, subString, String, InStr(String, findString), m
MsgBox % subString
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,089:
{{trans|AutoHotKey}}
 
<langsyntaxhighlight lang="awk">BEGIN {
str = "abcdefghijklmnopqrstuvwxyz"
n = 12
Line 1,099:
print substr(str, index(str, "q"), m)
print substr(str, index(str, "pq"), m)
}</langsyntaxhighlight>
 
{{out}}
Line 1,112:
{{improve|Axe|Add an example for substring start index.}}
 
<langsyntaxhighlight lang="axe">Lbl SUB1
0→{r₁+r₂+r₃}
r₁+r₂
Line 1,130:
0→{r₁+I+r₃}
r₁+I
Return</langsyntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QBasic}}
<lang qbasic>DIM baseString AS STRING, subString AS STRING, findString AS STRING
DIM m AS INTEGER, n AS INTEGER
 
baseString = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
 
' starting from n characters in and of m length;
subString = MID$(baseString, n, m)
PRINT subString
 
' starting from n characters in, up to the end of the string;
subString = MID$(baseString, n)
PRINT subString
 
' whole string minus last character;
subString = LEFT$(baseString, LEN(baseString) - 1)
PRINT subString
 
' starting from a known character within the string and of m length;
subString = MID$(baseString, INSTR(baseString, "b"), m)
PRINT subString
 
' starting from a known substring within the string and of m length.
findString = "pq"
subString = MID$(baseString, INSTR(baseString, findString), m)
PRINT subString
</lang>
 
{{out}}
<pre>
lmnop
lmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
bcdef
pqrst
</pre>
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight lang="basic">0 READ N, M, S$ : L = LEN(S$) : GOSUB 1 : END : DATA 5,11,THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG,J,FOX
 
REM starting from n characters in and of m length;
Line 1,191 ⟶ 1,152:
 
6 FOR I = 1 TO L : IF MID$(S$,I,LEN(F$)) = F$ THEN PRINT MID$(S$,I,M) : RETURN
7 NEXT : RETURN</langsyntaxhighlight>
 
==={{header|ASIC}}===
<syntaxhighlight lang="basic">REM Substring
Base$ = "abcdefghijklmnopqrstuvwxyz"
N = 12
M = 5
 
REM Starting from N characters in and of M length.
Sub$ = MID$(Base$, N, M)
PRINT Sub$
 
REM Starting from N characters in, up to the end of the string.
L = LEN(Base$)
L = L - N
L = L + 1
Sub$ = MID$(Base$, N, L)
PRINT Sub$
 
REM Whole string minus last character.
L = LEN(Base$)
L = L - 1
Sub$ = LEFT$(Base$, L)
PRINT Sub$
 
REM Starting from a known character within the string and of M length.
B = INSTR(Base$, "b")
Sub$ = MID$(Base$, B, M)
PRINT Sub$
 
REM Starting from a known substring within the string and of M length.
Find$ = "pq"
B = INSTR(Base$, Find$)
Sub$ = MID$(Base$, B, M)
PRINT Sub$
END
</syntaxhighlight>
{{out}}
<pre>
lmnop
lmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
bcdef
pqrst
</pre>
 
==={{header|BASIC256}}===
<langsyntaxhighlight BASIC256lang="basic256">c$ = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
Line 1,207 ⟶ 1,213:
f$ = "pq"
print mid(c$, instr(c$, f$), m)
end</langsyntaxhighlight>
{{out}}
<pre>lmnop
Line 1,215 ⟶ 1,221:
pqrst</pre>
 
==={{header|TrueBBC BASIC}}===
<langsyntaxhighlight qbasiclang="bbcbasic">LET basestring$ = "abcdefghijklmnopqrstuvwxyzThe five boxing wizards jump quickly"
LET n% = 1210
LET m% = 5
! starting from n characters in and of m length;
REM starting from n characters in and of m length:
PRINT (basestring$)[n:n + m - 1]
substring$ = MID$(basestring$, n%, m%)
! starting from n characters in, up to the end of the string;
PRINT substring$
PRINT (basestring$)[n:MAXNUM]
! whole string minus last character;
REM starting from n characters in, up to the end of the string:
PRINT (basestring$)[1:LEN(basestring$) - 1]
substring$ = MID$(basestring$, n%)
! starting from a known character within the string and of m length;
PRINT substring$
PRINT (basestring$)[POS(basestring$,"b"):POS(basestring$,"b") + m - 1]
! starting from a known subString$ within the string and of m length.
REM whole string minus last character:
LET findstring$ = "pq"
substring$ = LEFT$(basestring$)
PRINT (basestring$)[POS(basestring$,findstring$):POS(basestring$,findstring$) + m - 1]
PRINT substring$
END</lang>
REM starting from a known character within the string and of m length:
char$ = "w"
substring$ = MID$(basestring$, INSTR(basestring$, char$), m%)
PRINT substring$
REM starting from a known substring within the string and of m length:
find$ = "iz"
substring$ = MID$(basestring$, INSTR(basestring$, find$), m%)
PRINT substring$</syntaxhighlight>
{{out}}
<pre>boxin
boxing wizards jump quickly
The five boxing wizards jump quickl
wizar
izard</pre>
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="basic">10 REM SUBSTRING ... ROSETTACODE.ORG
20 A$ = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
30 X$ = "J" : S$ = "FOX"
Line 1,262 ⟶ 1,284:
280 GOTO 260
290 PRINT RIGHT$(A$,LEN(A$)+1-I)
300 END</langsyntaxhighlight>
 
{{out}}
Line 1,283 ⟶ 1,305:
STARTING FROM 'FOX' AND OF 11 LENGTH:
FOX JUMPS OVER THE LAZY DOG
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim s As String = "123456789"
Dim As Integer n = 3, m = 4
Print Mid(s, n, m)
Print Mid(s, n)
Print Left(s, Len(s) - 1)
'start from "5" say
Print Mid(s, Instr(s, "5"), m)
' start from "12" say
Print Mid(s, Instr(s, "12"), m)
Sleep</syntaxhighlight>
 
{{out}}
<pre>
3456
3456789
12345678
5678
1234
</pre>
 
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
 
void local fn DoIt
CFStringRef string = @"abcdefghijklmnopqrstuvwxyz"
NSLog(@"%@",mid(string,3,6))
NSLog(@"%@",fn StringSubstringFromIndex( string, 10 ))
NSLog(@"%@",left(string,len(string)-1))
CFRange range = fn StringRangeOfString( string, @"r" )
NSLog(@"%@",mid(string,range.location,6))
range = fn StringRangeOfString( string, @"pqr" )
NSLog(@"%@",mid(string,range.location,7))
end fn
 
fn DoIt
 
HandleEvents</syntaxhighlight>
 
{{out}}
<pre>
defghi
klmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
rstuvw
pqrstuv
</pre>
 
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=d4baf4adccd2220f63a1019695e072b0 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sString As String = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
 
Print Mid(sString, 11, 5) 'Starting from n characters in and of m length
Print Mid(sString, 17) 'Starting from n characters in, up to the end of the string
Print Left(sString, -1) 'Whole string minus last character
Print Mid(sString, InStr(sString, "B"), 9) 'Starting from a known character within the string and of m length
Print Mid(sString, InStr(sString, "OVER"), 8) 'Starting from a known substring within the string and of m length
 
End</syntaxhighlight>
Output:
<pre>
BROWN
FOX JUMPS OVER THE LAZY DOG
THE QUICK BROWN FOX JUMPS OVER THE LAZY DO
BROWN FOX
OVER THE
</pre>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 LET A$="abcdefghijklmnopqrstuvwxyz"
110 LET N=10:LET M=7
120 PRINT A$(N:N+M-1)
Line 1,294 ⟶ 1,392:
160 PRINT A$(I:I+M-1)
170 LET I=POS(A$,"ijk")
180 PRINT A$(I:I+M-1)</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">'These tasks can be completed with various combinations of Liberty Basic's
'built in Mid$()/ Instr()/ Left$()/ Right$()/ and Len() functions, but these
'examples only use the Mid$()/ Instr()/ and Len() functions.
 
baseString$ = "Thequickbrownfoxjumpsoverthelazydog."
n = 12
m = 5
 
'starting from n characters in and of m length
Print Mid$(baseString$, n, m)
 
'starting from n characters in, up to the end of the string
Print Mid$(baseString$, n)
 
'whole string minus last character
Print Mid$(baseString$, 1, (Len(baseString$) - 1))
 
'starting from a known character within the string and of m length
Print Mid$(baseString$, Instr(baseString$, "f", 1), m)
 
'starting from a known substring within the string and of m length
Print Mid$(baseString$, Instr(baseString$, "jump", 1), m)</syntaxhighlight>
 
==={{header|Nascom BASIC}}===
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="basic">
10 REM Substring
20 BAS$="abcdefghijklmnopqrstuvwxyz"
30 N=12:M=5
40 REM Starting from N characters in
50 REM and of M length
60 SB$=MID$(BAS$,N,M)
70 PRINT SB$
80 REM Starting from N characters in,
90 REM up to the end of the string
100 SB$=MID$(BAS$,N,LEN(BAS$)-N+1)
110 PRINT SB$
120 REM Whole string minus last character
130 SB$=LEFT$(BAS$,LEN(BAS$)-1)
140 PRINT SB$
150 REM Starting from a known character
160 REM within the string and of M length
170 A$=BAS$:B$="b":GOSUB 270
180 SB$=MID$(BAS$,C,M)
190 PRINT SB$
200 REM Starting from a known substring
210 REM within the string and of M length
220 A$=BAS$:B$="pq":GOSUB 270
230 SB$=MID$(BAS$,C,M)
240 PRINT SB$
250 END
260 REM ** INSTR subroutine
270 LB=LEN(B$):C=0
280 FOR I=1 TO LEN(A$)-LB+1
290 IF MID$(A$,I,LB)=B$ THEN C=I:RETURN
300 NEXT I
310 RETURN
</syntaxhighlight>
{{out}}
<pre>
lmnop
lmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
bcdef
pqrst
</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">If OpenConsole()
 
Define baseString.s, m, n
baseString = "Thequickbrownfoxjumpsoverthelazydog."
n = 12
m = 5
;Display the substring starting from n characters in and of m length.
PrintN(Mid(baseString, n, m))
;Display the substring starting from n characters in, up to the end of the string.
PrintN(Mid(baseString, n)) ;or PrintN(Right(baseString, Len(baseString) - n))
;Display the substring whole string minus last character
PrintN(Left(baseString, Len(baseString) - 1))
;Display the substring starting from a known character within the string and of m length.
PrintN(Mid(baseString, FindString(baseString, "b", 1), m))
 
;Display the substring starting from a known substring within the string and of m length.
PrintN(Mid(baseString, FindString(baseString, "ju", 1), m))
 
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</syntaxhighlight>
{{out}}
<pre>wnfox
wnfoxjumpsoverthelazydog.
Thequickbrownfoxjumpsoverthelazydog
brown
jumps</pre>
 
==={{header|QB64}}===
<syntaxhighlight lang="qb64">
DefStr S
DefInt I
string1 = "abcdefghijklmnopqrstuvwxyz"
substring = "klm"
Dim Achar As String * 1
Istart = 6
Ilength = 10
Achar = "c"
 
' starting from n characters in and of m length;
Print Mid$(string1, Istart, Ilength)
' starting from n characters in, up to the end of the string;
Print Mid$(string1, Istart)
Print Right$(string1, Len(string1) - Istart + 1)
' whole string minus the last character;
Print Left$(string1, Len(string1) - 1)
Print Mid$(string1, 1, Len(string1) - 1)
' starting from a known character within the string and of m length;
Print Mid$(string1, InStr(string1, Achar), Ilength)
' starting from a known substring within the string and of m length.
Print Mid$(string1, InStr(string1, substring), Ilength)
End
</syntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">DIM baseString AS STRING, subString AS STRING, findString AS STRING
DIM m AS INTEGER, n AS INTEGER
 
baseString = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
 
' starting from n characters in and of m length;
subString = MID$(baseString, n, m)
PRINT subString
 
' starting from n characters in, up to the end of the string;
subString = MID$(baseString, n)
PRINT subString
 
' whole string minus last character;
subString = LEFT$(baseString, LEN(baseString) - 1)
PRINT subString
 
' starting from a known character within the string and of m length;
subString = MID$(baseString, INSTR(baseString, "b"), m)
PRINT subString
 
' starting from a known substring within the string and of m length.
findString = "pq"
subString = MID$(baseString, INSTR(baseString, findString), m)
PRINT subString
</syntaxhighlight>
 
{{out}}
<pre>
lmnop
lmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
bcdef
pqrst
</pre>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">n = 2
m = 3
s$ = "abcd"
a$ = mid$(a$,n,m) ' starting from n characters in and of m length
a$ = mid$(a$,n) ' starting from n characters in, up to the end of the string
a$ = Print mid$(a$,1,(len(a$)-1)) ' whole string minus last character
a$ = mid$(a$,instr(a$,s$,1),m) ' starting from a known character within the string and of m length
a$ = mid$(a$,instr(a$,s$,1), m) ' starting from a known substring within the string and of m length.</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET basestring$ = "abcdefghijklmnopqrstuvwxyz"
LET n = 12
LET m = 5
! starting from n characters in and of m length;
PRINT (basestring$)[n:n + m - 1]
! starting from n characters in, up to the end of the string;
PRINT (basestring$)[n:MAXNUM]
! whole string minus last character;
PRINT (basestring$)[1:LEN(basestring$) - 1]
! starting from a known character within the string and of m length;
PRINT (basestring$)[POS(basestring$,"b"):POS(basestring$,"b") + m - 1]
! starting from a known subString$ within the string and of m length.
LET findstring$ = "pq"
PRINT (basestring$)[POS(basestring$,findstring$):POS(basestring$,findstring$) + m - 1]
END</syntaxhighlight>
 
==={{header|VBA}}===
{{trans|Phix}}<syntaxhighlight lang="vb">Public Sub substring()
'(1) starting from n characters in and of m length;
'(2) starting from n characters in, up to the end of the string;
'(3) whole string minus last character;
'(4) starting from a known character within the string and of m length;
'(5) starting from a known substring within the string and of m length.
sentence = "the last thing the man said was the"
n = 10: m = 5
'(1)
Debug.Print Mid(sentence, n, 5)
'(2)
Debug.Print Right(sentence, Len(sentence) - n + 1)
'(3)
Debug.Print Left(sentence, Len(sentence) - 1)
'(4)
k = InStr(1, sentence, "m")
Debug.Print Mid(sentence, k, 5)
'(5)
k = InStr(1, sentence, "aid")
Debug.Print Mid(sentence, k, 5)
End Sub</syntaxhighlight>{{out}}
<pre>thing
thing the man said was the
the last thing the man said was th
man s
aid w</pre>
 
==={{header|VBScript}}===
<syntaxhighlight lang="vb">
s = "rosettacode.org"
 
'starting from n characters in and of m length
WScript.StdOut.WriteLine Mid(s,8,4)
 
'starting from n characters in, up to the end of the string
WScript.StdOut.WriteLine Mid(s,8,Len(s)-7)
 
'whole string minus last character
WScript.StdOut.WriteLine Mid(s,1,Len(s)-1)
 
'starting from a known character within the string and of m length
WScript.StdOut.WriteLine Mid(s,InStr(1,s,"c"),4)
 
'starting from a known substring within the string and of m length
WScript.StdOut.WriteLine Mid(s,InStr(1,s,"ose"),6)
</syntaxhighlight>
 
{{Out}}
<pre>
code
code.org
rosettacode.or
code
osetta
</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">c$ = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
// starting from n characters in and of m length;
print mid$(c$, n, m)
// starting from n characters in, up to the end of the string;
print mid$(c$, n)
// whole string minus last character;
print left$(c$, len(c$) - 1)
// starting from a known character within the string and of m length;
print mid$(c$, instr(c$, "b"), m)
// starting from a known substring within the string and of m length.
f$ = "pq"
print mid$(c$, instr(c$, f$), m)
end</syntaxhighlight>
{{out}}
<pre>lmnop
lmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
bcdef
pqrst</pre>
 
==={{header|ZX Spectrum Basic}}===
ZX Spectrum Basic has unfortunately no direct way to find a substring within a string, however a similar effect can be done searching with a for loop:
<langsyntaxhighlight lang="zxbasic">10 LET A$="abcdefghijklmnopqrstuvwxyz"
15 LET n=10: LET m=7
20 PRINT A$(n TO n+m-1)
Line 1,310 ⟶ 1,686:
100 IF A$(i TO i+LEN (B$)-1)=B$ THEN PRINT A$(i TO i+m-1): LET i=LEN (A$)-LEN (B$)+1: GO TO 110
110 NEXT i
120 STOP </langsyntaxhighlight>
 
Without superfluous code:
<langsyntaxhighlight lang="zxbasic">10 LET A$="abcdefghijklmnopqrstuvwxyz": LET la=LEN A$
20 LET n=10: LET m=7
30 PRINT A$(n TO n+m-1)
Line 1,324 ⟶ 1,700:
100 FOR i=1 TO la-lb+1
110 IF A$(i TO i+lb-1)=B$ THEN PRINT A$(i TO i+m-1): LET i=la-lb+1
120 NEXT i</langsyntaxhighlight>
{{out}}
<pre>jklmnop
Line 1,331 ⟶ 1,707:
ghijklm
ijklmno</pre>
 
==={{header|BBC BASIC}}===
<lang bbcbasic> basestring$ = "The five boxing wizards jump quickly"
n% = 10
m% = 5
REM starting from n characters in and of m length:
substring$ = MID$(basestring$, n%, m%)
PRINT substring$
REM starting from n characters in, up to the end of the string:
substring$ = MID$(basestring$, n%)
PRINT substring$
REM whole string minus last character:
substring$ = LEFT$(basestring$)
PRINT substring$
REM starting from a known character within the string and of m length:
char$ = "w"
substring$ = MID$(basestring$, INSTR(basestring$, char$), m%)
PRINT substring$
REM starting from a known substring within the string and of m length:
find$ = "iz"
substring$ = MID$(basestring$, INSTR(basestring$, find$), m%)
PRINT substring$</lang>
{{out}}
<pre>boxin
boxing wizards jump quickly
The five boxing wizards jump quickl
wizar
izard</pre>
 
=={{header|BQN}}==
Line 1,369 ⟶ 1,712:
 
<code>↑</code>(take) and <code>↓</code>(drop) are the main tools to use here. In CBQN these produce a slice type and thus take constant time regardless of the size of the argument or result.
<langsyntaxhighlight lang="bqn"> 5↑3↓"Marshmallow"
"shmal"
3↓"Marshmallow"
Line 1,378 ⟶ 1,721:
"mallow"
(⊑∘/"sh"⊸⍷)⊸↓"Marshmallow"
"shmallow"</langsyntaxhighlight>
 
=={{header|Bracmat}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="bracmat">( (basestring = "The five boxing wizards jump quickly")
& (n = 10)
& (m = 5)
Line 1,408 ⟶ 1,751:
& out$!substring
&
)</langsyntaxhighlight>
{{out}}
<pre>boxin
Line 1,417 ⟶ 1,760:
 
=={{header|Burlesque}}==
<langsyntaxhighlight lang="blsq">
blsq ) "RosettaCode"5.+
"Roset"
Line 1,430 ⟶ 1,773:
blsq ) "RosettaCode"[-
"osettaCode"
</syntaxhighlight>
</lang>
 
Selecting/Deleting individual characters
 
<langsyntaxhighlight lang="blsq">
blsq ) "RosettaCode"{0 1 3 5}si
"Roet"
blsq ) "RosettaCode"{0 1 3 5}di
"oetaCde"
</syntaxhighlight>
</lang>
 
=={{header|C}}==
===C: ASCII version===
<syntaxhighlight lang="c">/*
<lang C>/*
* RosettaCode: Substring, C89
*
Line 1,494 ⟶ 1,837:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
===C: Unicode version===
<langsyntaxhighlight lang="c">/*
* RosettaCode: Substring, C89, Unicode
*
Line 1,552 ⟶ 1,895:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
===C: another version===
<langsyntaxhighlight lang="c">#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
Line 1,628 ⟶ 1,971:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
 
Line 1,648 ⟶ 1,991:
std::cout << s.substr(s.find(c), m) << "\n";
std::cout << s.substr(s.find(sub), m) << "\n";
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
namespace SubString
{
Line 1,676 ⟶ 2,019:
}
}
}</langsyntaxhighlight>
 
As of C# 8, we can use the Range syntax. Cases B and C can be written more succinctly.
<langsyntaxhighlight lang="csharp">
// B: starting from n characters in, up to the end of the string;
Console.WriteLine(s[n..]);
// C: whole string minus the last character;
Console.WriteLine(s[..^1]);
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">
 
(def string "alphabet")
Line 1,711 ⟶ 2,054:
(println
(subs string pos (+ pos m)))) ;phab
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. substring.
 
Line 1,769 ⟶ 2,112:
.
 
end program substring.</langsyntaxhighlight>
{{out}}
<pre>prompt$ cobc -xj substring.cob
Line 1,781 ⟶ 2,124:
=={{header|ColdFusion}}==
=== Classic tag based CFML ===
<langsyntaxhighlight lang="cfm">
<cfoutput>
<cfset str = "abcdefg">
Line 1,804 ⟶ 2,147:
 
</cfoutput>
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 1,815 ⟶ 2,158:
 
=== Script Based CFML ===
<langsyntaxhighlight lang="cfm"><cfscript>
str="abcdefg";
n = 2;
Line 1,835 ⟶ 2,178:
startingIndexSubString = find( "bc", str );
writeOutput( mid( str, startingIndexSubString, m ) );
</cfscript></langsyntaxhighlight>
{{Output}}
<pre>
Line 1,847 ⟶ 2,190:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(let ((string "0123456789")
(n 2)
(m 3)
Line 1,858 ⟶ 2,201:
(subseq string pos (+ pos m)))
(let ((pos (search substring string)))
(subseq string pos (+ pos m)))))</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Substrings;
IMPORT StdLog,Strings;
Line 1,888 ⟶ 2,231:
 
END Substrings.
</syntaxhighlight>
</lang>
Execute: ^Q Substrings.Do <br/>
{{out}}
Line 1,900 ⟶ 2,243:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">def substring_demo(string, n, m, known_character, known_substring)
n -= 1
 
Line 1,916 ⟶ 2,259:
end
 
substring_demo("crystalline", 3, 5, 't', "st")</langsyntaxhighlight>
 
{{out}}
Line 1,927 ⟶ 2,270:
=={{header|D}}==
{{works with|D|2}}
<langsyntaxhighlight lang="d">import std.stdio, std.string;
 
void main() {
Line 1,944 ⟶ 2,287:
const j = s.indexOf("qu");
writeln(s[j .. j + m]);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,955 ⟶ 2,298:
 
=={{header|DBL}}==
<langsyntaxhighlight DBLlang="dbl">;starting from n characters in and of m length;
SUB_STR = STR(n:m)
Line 1,966 ⟶ 2,309:
;starting from a known character f within the string and of m length;
;starting from a known substring f within the string and of m length.
SUB_STR = STR(%INSTR(1,STR,f):m)</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program ShowSubstring;
 
{$APPTYPE CONSOLE}
Line 1,987 ⟶ 2,330:
Writeln(Copy(s, Pos(c, s), m)); // starting from a known character within the string and of m length;
Writeln(Copy(s, Pos(sub, s), m)); // starting from a known substring within the string and of m length.
end.</langsyntaxhighlight>
 
{{out}}
Line 1,997 ⟶ 2,340:
 
=={{header|Dyalect}}==
<langsyntaxhighlight lang="dyalect">let s = "0123456789"
let n = 3
let m = 2
Line 2,012 ⟶ 2,355:
print(s.Substring(s.IndexOf(c),m))
// E: starting from a known substring within the string and of m length.
print(s.Substring(s.IndexOf(z),m))</langsyntaxhighlight>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def string := "aardvarks"
def n := 4
def m := 4
Line 2,022 ⟶ 2,365:
println(string(0, string.size() - 1))
println({string(def i := string.indexOf1('d'), i + m)})
println({string(def i := string.startOf("ard"), i + m)})</langsyntaxhighlight>
{{out}}
vark
Line 2,032 ⟶ 2,375:
=={{header|EasyLang}}==
 
<syntaxhighlight>
<lang>a$ = "2019-05-22 22:54:22"
a$ = timestr systime
print substr a$ 11 5
print substr a$ 1112 -1</lang>5
print substr a$ 12 99
<pre>
#
22:54
a$ = "Hallo Österreich!"
22:54:22
print substr a$ 1 (len a$ - 1)
</pre>
#
c$ = "Ö"
m = 2
i = 1
while substr a$ i 1 <> c$
i += 1
.
print substr a$ i m
#
c$ = "re"
m = 5
i = 1
while substr a$ i len c$ <> c$
i += 1
.
print substr a$ i m
</syntaxhighlight>
 
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
<lang ECL>
/* In this task display a substring:
Line 2,074 ⟶ 2,434:
defg
*/
</syntaxhighlight>
</lang>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="ecstasy">
module Substrings {
void run(String[] args = []) {
@Inject Console console;
if (args.size < 4) {
console.print(
$|
|Usage:
|
| xec Substrings <str> <offset> <count> <substr>
|
);
return;
}
 
String s = args[0];
Int n = new Int(args[1]);
Int m = new Int(args[2]);
String sub = args[3];
Char c = sub[0];
 
console.print($|
|{s .quoted()=}
|{substring(s, n, m ).quoted()=}
|{substring(s, n ).quoted()=}
|{substring(s ).quoted()=}
|{substring(s, c, m ).quoted()=}
|{substring(s, sub, m).quoted()=}
|
);
}
 
// starting from n characters in and of m length
static String substring(String s, Int n, Int m) {
assert 0 <= n <= n+m;
return n < s.size ? s[n..<(n+m).notGreaterThan(s.size)] : "";
}
 
// starting from n characters in, up to the end of the string
static String substring(String s, Int n) {
assert 0 <= n;
return s.substring(n);
}
 
// whole string minus the last character
static String substring(String s) {
return s.size > 1 ? s[0..<s.size-1] : "";
}
 
// starting from a known character within the string and of m length
static String substring(String s, Char c, Int m){
assert 0 <= m;
return substring(s, s.indexOf(c) ?: 0, m);
}
 
// starting from a known substring within the string and of m length
static String substring(String s, String sub, Int m){
assert 0 <= m;
return substring(s, s.indexOf(sub) ?: 0, m);
}
}
</syntaxhighlight>
 
{{out}}
<pre>
x$ xec doc/examples/Substrings scaryaardvark 5 4 ard
 
s .quoted()="scaryaardvark"
substring(s, n, m ).quoted()="aard"
substring(s, n ).quoted()="aardvark"
substring(s ).quoted()="scaryaardvar"
substring(s, c, m ).quoted()="arya"
substring(s, sub, m).quoted()="ardv"
</pre>
 
=={{header|Eero}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main()
Line 2,089 ⟶ 2,525:
Log( '%@', str.substringFromIndex: n ) // cdefgh
Log( '%@', str[(str.rangeOfString:'b').location .. m] ) // bcd
return 0</langsyntaxhighlight>
 
=={{header|Eiffel}}==
 
[https://github.com/ljr1981/rosettacode_answers/blob/main/testing/rc_substring/rc_substring_test_set.e Github Test code]
 
[https://youtu.be/7X-ix3Z7t-o Explainer video - 2 mins]
 
[https://youtu.be/zuCmC4BuPFU Substring feature explainer video - 1 min]
 
Each task in the description is coded with one or two lines of setup and then a pair of assertions to ensure that the proper result from the substring call. Because the {STRING} class in Eiffel is high-level, it covers both 8-bit and 32-bit strings (ASC and Unicode). If one wants to specifically code for Unicode, all one really needs to do is use {STRING_32} in the space of {STRING}.
 
<syntaxhighlight lang="eiffel">
class
RC_SUBSTRING_TEST_SET
 
inherit
TEST_SET_SUPPORT
 
feature -- Test routines
 
rc_substring_test
-- New test routine
note
task: "[
Display a substring:
 
- starting from n characters in and of m length;
- starting from n characters in, up to the end of the string;
- whole string minus the last character;
- starting from a known character within the string and of m length;
- starting from a known substring within the string and of m length.
]"
testing:
"execution/isolated",
"execution/serial"
local
str, str2: STRING
n, m: INTEGER
do
str := "abcdefgh"
 
m := 2
 
-- starting from n characters in and of m length;
n := str.index_of ('e', 1)
str2 := str.substring (n, n + m - 1)
assert_strings_equal ("start_n", "ef", str2)
assert_integers_equal ("m_length_1", 2, str2.count)
 
-- starting from n characters in, up to the end of the string;
str2 := str.substring (n, n + (str.count - n))
assert_strings_equal ("start_n_to_end", "efgh", str2)
assert_integers_equal ("len_1a", 4, str2.count)
 
-- whole string minus the last character;
str2 := str.substring (1, str.count - 1)
assert_strings_equal ("one_less_than_whole", "abcdefg", str2)
assert_integers_equal ("len_1b", 7, str2.count)
 
-- starting from a known character within the string and of m length;
n := str.index_of ('d', 1)
str2 := str.substring (n, n + m - 1)
assert_strings_equal ("known_char", "de", str2)
assert_integers_equal ("m_length_2", 2, str2.count)
 
-- starting from a known substring within the string and of m length.
n := str.substring_index ("bc", 1)
str2 := str.substring (n, n + m - 1)
assert_strings_equal ("known_substr", "bc", str2)
assert_integers_equal ("m_length_3", 2, str2.count)
end
 
end
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang="elena">import extensions;
public program()
Line 2,108 ⟶ 2,618:
console.writeLine(s.Substring(s.indexOf(0, c), m));
console.writeLine(s.Substring(s.indexOf(0, z), m))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,119 ⟶ 2,629:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">s = "abcdefgh"
String.slice(s, 2, 3) #=> "cde"
String.slice(s, 1..3) #=> "bcd"
Line 2,130 ⟶ 2,640:
String.slice(s, 1..3) #=> "βγδ"
String.slice(s, -3, 2) #=> "ζη"
String.slice(s, 3..-1) #=> "δεζηθ"</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 2,152 ⟶ 2,662:
 
=={{header|Euphoria}}==
<langsyntaxhighlight Euphorialang="euphoria">sequence baseString, subString, findString
integer findChar
integer m, n
Line 2,190 ⟶ 2,700:
subString = baseString[n..n+m-1]
puts(1, subString )
puts(1,'\n')</langsyntaxhighlight>
 
{{out}}
Line 2,200 ⟶ 2,710:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">[<EntryPoint>]
let main args =
let s = "一二三四五六七八九十"
Line 2,212 ⟶ 2,722:
printfn "%s" (s.Substring(s.IndexOf(c), m))
printfn "%s" (s.Substring(s.IndexOf(z), m))
0</langsyntaxhighlight>
{{out}}
<pre>四五
Line 2,221 ⟶ 2,731:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: math sequences kernel ;
 
! starting from n characters in and of m length
Line 2,240 ⟶ 2,750:
 
! starting from a known substring within the string and of m length.
: subseq-from-seq ( subseq len seq -- seq ) [ start ] subseq-from-* ;</langsyntaxhighlight>
 
=={{header|Falcon}}==
'''VBA/Python programmer's approach not sure if it's the most falconic way'''
<langsyntaxhighlight lang="falcon">
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 2,258 ⟶ 2,768:
new_n = s.find("mu", 0)
> "starting from a known character within the string and of m length: ", s[new_n:new_n+m]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,272 ⟶ 2,782:
/STRING and SEARCH are standard words. [http://home.earthlink.net/~neilbawd/tool2002.txt SCAN] is widely implemented. Substrings represented by address/length pairs require neither mutation nor allocation.
 
<langsyntaxhighlight lang="forth">2 constant Pos
3 constant Len
: Str ( -- c-addr u ) s" abcdefgh" ;
Line 2,280 ⟶ 2,790:
Str 1- type \ abcdefg
Str char d scan drop Len type \ def
Str s" de" search 2drop Len type \ def</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program test_substring
 
character (*), parameter :: string = 'The quick brown fox jumps over the lazy dog.'
Line 2,307 ⟶ 2,817:
write (*, '(a)') string (i : i + m - 1)
 
end program test_substring</langsyntaxhighlight>
{{out}}
quick brown fox
Line 2,317 ⟶ 2,827:
 
=={{header|Free Pascal}}==
<langsyntaxhighlight lang="pascal">s[n..n+m]
s[n..high(nativeUInt)]
s[1..length(s)-1]
s[pos(c, s)..pos(c, s)+m]
s[pos(p, s)..pos(p, s)+m]</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
 
Dim s As String = "123456789"
Dim As Integer n = 3, m = 4
Print Mid(s, n, m)
Print Mid(s, n)
Print Left(s, Len(s) - 1)
'start from "5" say
Print Mid(s, Instr(s, "5"), m)
' start from "12" say
Print Mid(s, Instr(s, "12"), m)
Sleep</lang>
 
{{out}}
<pre>
3456
3456789
12345678
5678
1234
</pre>
 
=={{header|Frink}}==
Line 2,351 ⟶ 2,838:
String indices are zero-based.
 
<langsyntaxhighlight lang="frink">test = "🐱abcdefg😾"
n = 3
m = 2
Line 2,363 ⟶ 2,850:
if pos != -1
println[substrLen[test, pos, m]]
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,372 ⟶ 2,859:
cd
cd
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=d4baf4adccd2220f63a1019695e072b0 Click this link to run this code]'''
<lang gambas>Public Sub Main()
Dim sString As String = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
 
Print Mid(sString, 11, 5) 'Starting from n characters in and of m length
Print Mid(sString, 17) 'Starting from n characters in, up to the end of the string
Print Left(sString, -1) 'Whole string minus last character
Print Mid(sString, InStr(sString, "B"), 9) 'Starting from a known character within the string and of m length
Print Mid(sString, InStr(sString, "OVER"), 8) 'Starting from a known substring within the string and of m length
 
End</lang>
Output:
<pre>
BROWN
FOX JUMPS OVER THE LAZY DOG
THE QUICK BROWN FOX JUMPS OVER THE LAZY DO
BROWN FOX
OVER THE
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">LETTERS;
# "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
LETTERS{[5 .. 10]};
# "EFGHIJ"</langsyntaxhighlight>
 
=={{header|Go}}==
===ASCII===
The task originally had no mention of unicode. This solution works with ASCII data.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,429 ⟶ 2,895:
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,443 ⟶ 2,909:
===UTF-8===
Strings are generally handled as UTF-8 in Go.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,471 ⟶ 2,937:
sx := strings.Index(s, ks)
fmt.Printf("Start %q, length %d: %s\n", ks, m, string([]rune(s[sx:])[:m]))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,485 ⟶ 2,951:
=={{header|Groovy}}==
Strings in Groovy are 0-indexed.
<langsyntaxhighlight lang="groovy">def str = 'abcdefgh'
def n = 2
def m = 3
Line 2,505 ⟶ 2,971:
println str[index2..index2+m-1]
/* or */
println str[index2..<(index2+m)]</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 2,525 ⟶ 2,991:
</pre>
*The last two can be formulated with the following function:
<langsyntaxhighlight Haskelllang="haskell">t45 n c s | null sub = []
| otherwise = take n. head $ sub
where sub = filter(isPrefixOf c) $ tails s</langsyntaxhighlight>
 
<pre>*Main> t45 3 "4" "1234567890"
Line 2,541 ⟶ 3,007:
Testing with an extended set of characters, and using '''Data.Text''' functions, including ''breakOn'':
{{works with|Haskell|8.0.2}}
<langsyntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
 
import qualified Data.Text as T (Text, take, drop, init, breakOn)
Line 2,571 ⟶ 3,037:
, fromStringForN 6 "大势"
] <*>
["天地不仁仁者人也🐒话说天下大势分久必合🍑合久必分🔥"])</langsyntaxhighlight>
{{Out}}
<pre>话说天下大势分久必合
Line 2,580 ⟶ 3,046:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">CHARACTER :: string = 'ABCDEFGHIJK', known = 'B', substring = 'CDE'
REAL, PARAMETER :: n = 5, m = 8
Line 2,591 ⟶ 3,057:
 
pos_substring = INDEX(string, substring)
WRITE(Messagebox) string(pos_substring : pos_substring+m-1), "| substring starting from pos_substring, length m"</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
write("Usage: substring <string> <first position> <second position> <single character> <substring>")
s := \arglist[1] | "aardvarks"
Line 2,607 ⟶ 3,073:
write( s[find(c,s)+:m] )
write( s[find(ss,s)+:m] )
end</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j"> 5{.3}.'Marshmallow'
shmal
3}.'Marshmallow'
Line 2,622 ⟶ 3,088:
mallo
5{.(}.~ I.@E.~&'sh')'Marshmallow'
shmal</langsyntaxhighlight>
 
Note that there are other, sometimes better, ways of accomplishing this task.
 
<langsyntaxhighlight Jlang="j"> 'Marshmallow'{~(+i.)/3 5
shmal</langsyntaxhighlight>
 
Or, probably more efficient when the desired substring is large:
 
<syntaxhighlight lang="j"> (,.3 5)];.0 'Marshmallow'
shmal</syntaxhighlight>
 
The <code>taketo</code> / <code>takeafter</code> and <code>dropto</code> / <code>dropafter</code> utilities from the <code>strings</code> script further simplify these types of tasks.
<langsyntaxhighlight Jlang="j"> require 'strings'
'sh' dropto 'Marshmallow'
shmallow
Line 2,636 ⟶ 3,107:
shmal
'sh' takeafter 'Marshmallow'
mallow</langsyntaxhighlight>
 
Note also that these operations work the same way on lists of numbers that they do on this example list of characters.
 
<langsyntaxhighlight Jlang="j"> 3}. 2 3 5 7 11 13 17 19
7 11 13 17 19
7 11 dropafter 2 3 5 7 11 13 17 19
2 3 5 7 11</langsyntaxhighlight>
 
=={{header|Java}}==
 
<langsyntaxhighlight lang="java">public static String Substring(String str, int n, int m){
return str.substring(n, n+m);
}
Line 2,662 ⟶ 3,133:
return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
Line 2,669 ⟶ 3,140:
*<code>substring(start, [end])</code> returns a string containing the substring from <code>start</code> up to, ''but not including'', <code>end</code>.
 
<langsyntaxhighlight lang="javascript">var str = "abcdefgh";
 
var n = 2;
Line 2,688 ⟶ 3,159:
 
// * starting from a known substring within the string and of m length.
str.substr(str.indexOf('bc'), m); // => "bcd"</langsyntaxhighlight>
 
 
Or, in terms of some familiar functional primitives, translating broadly from Haskell:
 
<langsyntaxhighlight AppleScriptlang="applescript">(function () {
'use strict';
 
Line 2,749 ⟶ 3,220:
}, null, 2);
 
})();</langsyntaxhighlight>
 
{{Out}}
 
<syntaxhighlight lang="javascript">{
<lang JavaScript>{
"from n in, of m length": "五六七",
"from n in, up to end": "四五六七八九十",
Line 2,759 ⟶ 3,230:
"from matching char, of m length": "五六七",
"from matching string, of m length": "六七八九"
}</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.4}}
For this exercise we use the Chinese characters for 1 to 10, the character for "10" being "十":
<langsyntaxhighlight lang="jq">def s: "一二三四五六七八九十";</langsyntaxhighlight>
 
jq strings are UTF-8 strings, and array-based string indexing and
most string functions, such as length/0, are based on Unicode code
points. However, the function index/1 currently uses character counts when its input is a string, and therefore in the following we use ix/1 defined as follows:
<langsyntaxhighlight lang="jq">def ix(s): explode | index(s|explode);</langsyntaxhighlight>
 
(Users who have access to the regex function match/1 can use it, as illustrated in the comments below.)
 
Since jq arrays and strings have an index origin of 0, "n characters in" is interpreted to require an index of (n+1).
<langsyntaxhighlight lang="jq"># starting from n characters in and of m length: .[n+1: n+m+1]
"s[1:2] => \( s[1:2] )",
Line 2,793 ⟶ 3,264:
# jq>1.4: match(sub).offset as $i | .[ $i: $i + m]
"s | ix(\"五六\") as $i | .[$i: $i + 2] => " +
"\( s | ix("五六") as $i | .[$i: $i + 2] )"</langsyntaxhighlight>
# {{Out}}
<langsyntaxhighlight lang="sh">$ jq -M -n -r -f Substring.jq
s[1:2] => 二
s[9:] => 十
s|.[0:length-1] => 一二三四五六七八九
s | ix("五") as $i | .[$i: $i + 1] => 五
s | ix("五六") as $i | .[$i: $i + 2] => 五六</langsyntaxhighlight>
 
=={{header|Jsish}}==
{{trans|Javascript}}
<langsyntaxhighlight lang="javascript">#!/usr/local/bin/jsish -u %s
 
var str = "abcdefgh";
Line 2,891 ⟶ 3,362:
 
})();
;res;</langsyntaxhighlight>
 
{{out}}
Line 2,914 ⟶ 3,385:
The initial --U is a run with echo mode. The '''-u -update true''' puts jsish in unit test mode, and will add a comparison block. After the test pass, the code file is changed to
 
<langsyntaxhighlight lang="javascript">#!/usr/local/bin/jsish -u %s
 
var str = "abcdefgh";
Line 3,016 ⟶ 3,487:
res ==> { "all but last":"abcdefg", "from 3 in, up to end":"defgh", "from 4 in, of length 3":"efg", "from matching b, of length 3":"bcd", "from matching bc, of length 4":"bcde" }
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 3,022 ⟶ 3,493:
<code>CharString("/'''\ʕ•ᴥ•ʔ/'''\"...)</code>. Without the CharString declaration, the string is interpreted as an UTF8 string with access through its byte representation.
 
<langsyntaxhighlight lang="julia">julia> s = "abcdefg"
"abcdefg"
 
Line 3,044 ⟶ 3,515:
 
julia> s[search(s,'c'):search(s,'c')+m]
"cde"</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Strings in Kotlin are 0-indexed:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 3,064 ⟶ 3,535:
i = s.indexOf(z)
println(s.substring(i, i + m))
}</langsyntaxhighlight>
 
{{out}}
Line 3,076 ⟶ 3,547:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 3,135 ⟶ 3,606:
_length "${str}" ${#foo} ${m}
echo
</syntaxhighlight>
</lang>
{{out}}<pre>
--String (Length: 50 chars):
Line 3,162 ⟶ 3,633:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{S.slice 1 2 hello brave new world}
-> brave new
{W.slice 4 11 www.rosetta.org}
-> rosetta
</syntaxhighlight>
</lang>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
$txt = The Lang programming language!
 
$n = 9
$m = 11
 
$c = p
 
$searchTxt = prog
 
fn.println(fn.substring($txt, $n, parser.op($n + $m)))
# Output: programming
 
fn.println(fn.substring($txt, $n))
# Output: programming language!
 
fn.println(fn.substring($txt, 0, parser.op(fn.len($txt) - 1)))
# Output: The Lang programming language
 
fn.println(fn.substring($txt, fn.indexOf($txt, $c), parser.op(fn.indexOf($txt, $c) + $m)))
# Output: programming
 
fn.println(fn.substring($txt, fn.indexOf($txt, $searchTxt), parser.op(fn.indexOf($txt, $searchTxt) + $m)))
# Output: programming
</syntaxhighlight>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: cr "\n". ; [] '__A set : dip swap __A swap 1 compress append '__A set execute __A
-1 extract nip ; : nip swap drop ; : tuck swap over ; : -rot rot rot ; : 0= 0 == ; : 1+ 1 + ;
: 2dip swap 'dip dip ; : 2drop drop drop ; : |a,b> over - iota + ; : bi* 'dip dip execute ; : bi@ dup bi* ;
Line 3,189 ⟶ 3,687:
str comb n str-tail
str "d" str-index m str <substr>
str "de" str-index m str <substr></langsyntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(str = 'The quick grey rhino jumped over the lazy green fox.')
 
//starting from n characters in and of m length;
Line 3,207 ⟶ 3,705:
 
//starting from a known substring within the string and of m length
#str->substring(#str->find('rhino'),12) //rhino jumped</langsyntaxhighlight>
 
=={{header|LFE}}==
Line 3,214 ⟶ 3,712:
From the LFE REPL:
 
<langsyntaxhighlight lang="lisp">
> (set n 3)
3
Line 3,233 ⟶ 3,731:
> (string:sub_string "abcdefghijklm" start-str (+ start-str m -1))
"efghi"
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<lang lb>'These tasks can be completed with various combinations of Liberty Basic's
'built in Mid$()/ Instr()/ Left$()/ Right$()/ and Len() functions, but these
'examples only use the Mid$()/ Instr()/ and Len() functions.
 
baseString$ = "Thequickbrownfoxjumpsoverthelazydog."
n = 12
m = 5
 
'starting from n characters in and of m length
Print Mid$(baseString$, n, m)
 
'starting from n characters in, up to the end of the string
Print Mid$(baseString$, n)
 
'whole string minus last character
Print Mid$(baseString$, 1, (Len(baseString$) - 1))
 
'starting from a known character within the string and of m length
Print Mid$(baseString$, Instr(baseString$, "f", 1), m)
 
'starting from a known substring within the string and of m length
Print Mid$(baseString$, Instr(baseString$, "jump", 1), m)</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">str = "The quick brown fox jumps over the lazy dog"
 
-- starting from n characters in and of m length
Line 3,289 ⟶ 3,763:
pos = offset(sub, str)
put str.char[pos..pos+m-1]
-- "fox jumps"</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">put "pple" into x
answer char 2 to char 5 of x // n = 2, m=5
answer char 2 to len(x) of x // n = 2, m = len(x), can also use -1
answer char 1 to -2 of x // n = 1, m = 1 less than length of string
answer char offset("p",x) to -1 of x // known char "p" to end of string
answer char offset("pl",x) to -1 of x // known "pl" to end of string</langsyntaxhighlight>
n.b. Offset also supports a third parameter "charsToSkip" allowing you to loop through subsequent matches of the substring.
 
Line 3,304 ⟶ 3,778:
 
The following are defined to behave similarly to the built-in index operator ITEM. As with most Logo list operators, these are designed to work for both words (strings) and lists.
<langsyntaxhighlight lang="logo">to items :n :thing
if :n >= count :thing [output :thing]
output items :n butlast :thing
Line 3,341 ⟶ 3,815:
print butlast :s ; abcdefg
print items 3 member "d :s ; def
print items 3 members "de :s ; def</langsyntaxhighlight>
 
=={{header|Logtalk}}==
Using atoms for representing strings and usng the same sample data as e.g. in the Java solution:
<langsyntaxhighlight lang="logtalk">
:- object(substring).
 
Line 3,367 ⟶ 3,841:
 
:- end_object.
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="text">
| ?- ?- substring::test('abcdefgh', 2, 3, 'b', 'bc').
cde
Line 3,377 ⟶ 3,851:
bcd
yes
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">str = "abcdefghijklmnopqrstuvwxyz"
n, m = 5, 15
 
Line 3,405 ⟶ 3,879:
if pos then print (str:sub(pos,pos+m)) end d-- ijklmnopqrstuvwx
 
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
Line 3,412 ⟶ 3,886:
Function for length always return length as Words (two bytes), so we can get half, if we have an odd number of ansi characters. For Utf16-le there is another Len function,Len.Disp which returns the needed positions for displaying characters. So Print LEN.DISP("aããz")=4 : Print Len("̃ãz")=4
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckAnsi {
\\ ANSI STRING
Line 3,461 ⟶ 3,935:
CheckUTF16LE
 
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
> n, m := 3, 5:
> s := "The Higher, The Fewer!":
> s[ n .. n + m - 1 ];
"e Hig"
</syntaxhighlight>
</lang>
There are a few ways to get everything from the n-th character on.
<syntaxhighlight lang="maple">
<lang Maple>
> s[ n .. -1 ] = s[ n .. ];
"e Higher, The Fewer!" = "e Higher, The Fewer!"
Line 3,477 ⟶ 3,951:
> StringTools:-Drop( s, n - 1 );
"e Higher, The Fewer!"
</syntaxhighlight>
</lang>
There are a few ways to get all but the last character.
<syntaxhighlight lang="maple">
<lang Maple>
> s[ 1 .. -2 ] = s[ .. -2 ];
"The Higher, The Fewer" = "The Higher, The Fewer"
Line 3,485 ⟶ 3,959:
> StringTools:-Chop( s );
"The Higher, The Fewer"
</syntaxhighlight>
</lang>
The <code>searchtext</code> command returns the position of a matching substring.
<syntaxhighlight lang="maple">
<lang Maple>
> pos := searchtext( ",", s ):
> s[ pos .. pos + m - 1 ];
Line 3,495 ⟶ 3,969:
> s[ pos .. pos + m - 1 ];
"Highe"
</syntaxhighlight>
</lang>
But, note that <code>searchtext</code> returns 0 when there is no match, and 0 is not a valid index into a string.
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The <code>StringTake</code> and <code>StringDrop</code> are relevant for this exercise.
<syntaxhighlight lang="mathematica">n = 2
<lang Mathematica>n = 2
m = 3
StringTake["Mathematica", {n+1, n+m-1}]
Line 3,509 ⟶ 3,983:
(* Similar to above *)
pos = StringPosition["Mathematica", "the"][[1]]
StringTake["Mathematica", {pos, pos+m-1}]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
Unicode, UTF-8, UTF-16 is only partially supported. In some cases, a conversion of unicode2native() or native2unicode() is necessary.
<syntaxhighlight lang="matlab">
<lang Matlab>
% starting from n characters in and of m length;
s(n+(1:m))
Line 3,526 ⟶ 4,000:
% starting from a known substring within the string and of m length.
s(strfind(s,pattern)+[0:m-1])
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">s: "the quick brown fox jumps over the lazy dog";
substring(s, 17);
/* "fox jumps over the lazy dog" */
substring(s, 17, 20);
/* "fox" */</langsyntaxhighlight>
 
=={{header|MUMPS}}==
MUMPS has the first position in a string numbered as 1.
<syntaxhighlight lang="mumps">
<lang MUMPS>
SUBSTR(S,N,M,C,K)
;show substring operations
Line 3,561 ⟶ 4,035:
W !,?5,$EXTRACT(S,X,X+M-1)
QUIT
</syntaxhighlight>
</lang>
Usage:
<pre>
Line 3,581 ⟶ 4,055:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">str = "test string"
 
println substr(str, m, m + n)
Line 3,587 ⟶ 4,061:
println substr(str, 0, len(str) - 1)
println substr(str, str.indexOf("s"), str.indexOf("s") + m)
println substr(str, str.indexOf("str"), str.indexOf("str") + m)</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 3,609 ⟶ 4,083:
WriteLine(s.Substring(s.IndexOf(z, 0, s.Length), m));
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols
Line 3,629 ⟶ 4,103:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 24ex; overflow:scroll;">
Line 3,641 ⟶ 4,115:
 
=={{header|newLISP}}==
<langsyntaxhighlight newLISPlang="newlisp">> (set 'str "alphabet" 'n 2 'm 4)
4
> ; starting from n characters in and of m length
Line 3,658 ⟶ 4,132:
> (slice str (find "ph" str) m)
"phab"
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
NilNim allows to work with raw strings, ignoring the encoding, or with UTF-8 strings. The following program shows how to extract substrings in both cases.
 
<langsyntaxhighlight lang="nim">import strformat, strutils, unicode
 
let
Line 3,678 ⟶ 4,152:
# ASCII strings.
# We can take a substring using "s.substr(first, last)" or "s[first..last]".
# The latter form can also be used as lvaluevalue to assign a substring.
 
echo "ASCII string: ", s1
Line 3,732 ⟶ 4,206:
echo &"Starting from substring “{cs2}” within the string and of m = {m} length: ", s2.runeSubStr(pos, m)
else:
echo &"String “{cs2}” not found."</langsyntaxhighlight>
 
{{out}}
Line 3,750 ⟶ 4,224:
 
=={{header|Niue}}==
<langsyntaxhighlight Niuelang="niue">( based on the JavaScript code )
'abcdefgh 's ;
s str-len 'len ;
Line 3,770 ⟶ 4,244:
( starting from a known substring within the string and of m length )
s s 'bc str-find dup m + substring . ( => bcd ) newline
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class SubString {
Line 3,792 ⟶ 4,266:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
From the interactive toplevel:
<langsyntaxhighlight lang="ocaml">$ ocaml
# let s = "ABCDEFGH" ;;
val s : string = "ABCDEFGH"
Line 3,819 ⟶ 4,293:
# let n = Str.search_forward (Str.regexp_string "DE") s 0 in
String.sub s n m ;;
- : string = "DEF"</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: substrings(s, n, m)
s sub(n, m) println
s right(s size n - 1 +) println
s left(s size 1 - ) println
s sub(s indexOf('d'), m) println
s sub(s indexOfAll("de"), m) println ;</langsyntaxhighlight>
 
{{out}}
Line 3,841 ⟶ 4,315:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {DropUntil Xs Prefix}
case Xs of nil then nil
Line 3,861 ⟶ 4,335:
{List.take {DropUntil Digits "31"} 3} = ""
]
System.showInfo}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 3,867 ⟶ 4,341:
{{Works with|PARI/GP|2.7.4 and above}}
 
<langsyntaxhighlight lang="parigp">
\\ Returns the substring of string str specified by the start position s and length n.
\\ If n=0 then to the end of str.
Line 3,891 ⟶ 4,365:
print("8.|",ssubstr("",1,4),"|");
}
</langsyntaxhighlight>
 
{{Output}}
Line 3,907 ⟶ 4,381:
 
=={{header|Pascal}}==
''See also [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]]''
{{works with|Extended Pascal}}
Remember, in Extended Pascal (ISO standard 10206), <tt>string(…)</tt> variables’ indices are <tt>1</tt>‑based.
Pay attention to the constraints below.
<syntaxhighlight lang="pascal">program substring(output);
var
sample: string(20) value 'Foobar';
n, m: integer value 1;
begin
{ starting from n characters in and of m length - - - - - - - - - - - - - - - }
writeLn(subStr(sample, n, m));
writeLn(subStr(sample, n):m);
writeLn(sample[n .. n + m - 1]);
{ starting from n characters in, up to the end of the string - - - - - - - - }
writeLn(subStr(sample, n));
writeLn(sample[n .. length(sample)]);
{ whole string minus the last character - - - - - - - - - - - - - - - - - - - }
writeLn(subStr(sample, 1, length(sample) - 1));
writeLn(sample[1 .. pred(length(sample))]);
writeLn(sample:length(sample) - 1);
{ To make this a permanent change you can use
writeStr(sample, sample:pred(length(sample)); }
{ starting from a known character within the string and of m length - - - - - }
writeLn(subStr(sample, index(sample, 'b'), m));
writeLn(subStr(sample, index(sample, 'b')):m);
writeLn(sample[index(sample, 'b') .. index(sample, 'b') + m - 1]);
{ starting from a known substring within the string and of m length - - - - - }
writeLn(subStr(sample, index(sample, 'bar'), m));
writeLn(subStr(sample, index(sample, 'bar')):m);
writeLn(sample[index(sample, 'bar') .. index(sample, 'bar') + m - 1]);
end.</syntaxhighlight>
* If a <tt>string(…)</tt> variable is designated <tt>bindable</tt>, for instance<syntaxhighlight lang="pascal">var myBindableStringVariable: bindable string(20);</syntaxhighlight>then it is not possible to use the <tt>array</tt>-like substring notation: That means<syntaxhighlight lang="pascal">myBindableStringVariable[firstCharacterIndex .. lastCharacterIndex]</syntaxhighlight>is not permitted since <tt>myBindableStringVariable</tt> is <tt>bindable</tt>.
* It is ''mandatory'' that in <tt>sample[firstCharacterIndex .. lastCharacterIndex]</tt> ''both'' <tt>firstCharacterIndex</tt> and <tt>lastCharacterIndex</tt> are non-descending and denote ''valid indices'' in <tt>sample</tt>. That means both need to be in the range <tt>1 .. length(sample)</tt>. However, for an empty string this range would be empty. Therefore, the array-like substring notation cannot be used for an empty string.
* In <tt>subStr(sample, firstCharacterIndex, substringLength)</tt> the <tt>substringLength</tt> has to be a non-negative integer less than or equal to <tt>length(sample)</tt>. However, <tt>firstCharacterIndex + substringLength ‑ 1</tt> may not exceed <tt>length(sample)</tt>. Therefore, if <tt>sample</tt> is an empty string, the only permissible <tt>firstCharacterIndex</tt> value is <tt>1</tt>&nbsp;(positive one) and the only permissible <tt>substringLength</tt> is <tt>0</tt>&nbsp;(zero). Needless to say how pointless <tt>subStr(&#39;', 1, 0)</tt> is.
* Furthermore, the <tt>totalWidth</tt> specification in <tt>write(myStringOrCharValue:totalWidth)</tt> (and <tt>writeLn</tt>/<tt>writeStr</tt> respectively) has to be greater than or equal to zero. To take advantage of this procedure in a fool-proof manner, you need to extend your width expression like this:<syntaxhighlight lang="pascal">write(sample:pred(length(sample), ord(length(sample) > 0))); { all but last char }</syntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my $str = 'abcdefgh';
print substr($str, 2, 3), "\n"; # Returns 'cde'
print substr($str, 2), "\n"; # Returns 'cdefgh'
print substr($str, 0, -1), "\n"; #Returns 'abcdefg'
print substr($str, index($str, 'd'), 3), "\n"; # Returns 'def'
print substr($str, index($str, 'de'), 3), "\n"; # Returns 'def'</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<lang Phix>(phixonline)-->
<syntaxhighlight lang="phix">
<span style="color: #000080;font-style:italic;">--(1) starting from n characters in and of m length;
--(21) starting from n characters in, up to the endand of them stringlength;
--(2) starting from n characters in, up to the end of the string;
--(3) whole string minus last character;
--(43) startingwhole fromstring aminus knownlast character within the string and of m length;
--(54) starting from a known substringcharacter within the string and of m length.; </span>
--(5) starting from a known substring within the string and of m length.
<span style="color: #008080;">constant</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: #0000FF;">,</span>
constant sentence = "the last thing the man said was the",
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5</span>
n = 10, m = 5
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span>
integer k, l
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">m</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
l = n+m-1
<span style="color: #008080;">if</span> <span style="color: #000000;">l</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: #008080;">then</span>
if l<=length(sentence) then
<span style="color: #0000FF;">?</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">..</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- (1)</span>
?sentence[n..l] -- (1)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">if</span> <span style="color: #000000;">n</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: #008080;">then</span>
if n<=length(sentence) then
<span style="color: #0000FF;">?</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- (2) or [n..$]</span>
?sentence[n..-1] -- (2) or [n..$]
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<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: #000000;">0</span> <span style="color: #008080;">then</span>
if length(sentence)>0 then
<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: #0000FF;">..-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- (3) or [1..$-1]</span>
?sentence[1..-2] -- (3) or [1..$-1]
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'m'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)</span>
k = find('m',sentence)
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">m</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
l = k+m-1
<span style="color: #008080;">if</span> <span style="color: #000000;">l</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: #008080;">then</span>
if l<=length(sentence) then
<span style="color: #0000FF;">?</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">..</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- (4)</span>
?sentence[k..l] -- (4)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"aid"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">)</span>
k = match("aid",sentence)
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">m</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
l = k+m-1
<span style="color: #008080;">if</span> <span style="color: #000000;">l</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: #008080;">then</span>
if l<=length(sentence) then
<span style="color: #0000FF;">?</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">..</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- (5)</span>
?sentence[k..l] -- (5)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<!--</lang>-->
</syntaxhighlight>
{{out}}
<pre>
Line 3,959 ⟶ 4,472:
</pre>
Alternative version with no error handling, for those in a hurry (same ouput):
<syntaxhighlight lang="phix">
<!--<lang Phix>-->
?sentence[n..n+m-1]
<span style="color: #0000FF;">?</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">..</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">m</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
?sentence[n..-1]
<span style="color: #0000FF;">?</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
?sentence[1..-2]
<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: #0000FF;">..-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span>
?(sentence[find('m',sentence)..$])[1..m]
<span style="color: #0000FF;">?(</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'m'</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: #0000FF;">..</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span>
?(sentence[match("aid",sentence)..$])[1..m]
<span style="color: #0000FF;">?(</span><span style="color: #000000;">sentence</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"aid"</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: #0000FF;">..</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span>
</syntaxhighlight>
<!--</lang>-->
If sentence is UTF-8 or UTF-16, you should explicitly use sequence utf32 = utf8_to_utf32(string utf8) or sequence utf32 = utf16_to_utf32(sequence utf16) before any slicing or find()/match(), and string utf8 = utf32_to_utf8(sequence utf32) or sequence utf16 = utf32_to_utf16(sequence utf32) before display. Note that unicode does not normally display correctly on a standard Windows console, but is fine in a GUI or Linux console or a web browser.
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
/#
Line 3,993 ⟶ 4,507:
dup -1 del ? /# (3) #/
'm' find m myslice ? /# (4) #/
"aid" find m myslice ? /# (5) #/</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$str = 'abcdefgh';
$n = 2;
Line 4,005 ⟶ 4,519:
echo substr($str, strpos($str, 'd'), $m), "\n"; //def
echo substr($str, strpos($str, 'de'), $m), "\n"; //def
?></langsyntaxhighlight>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
S = "Picat is fun",
N = 3,
Line 4,043 ⟶ 4,557:
% find is non-deterministic, hence the once/1
substring5(S,SS,M) = slice(S,Start,Start+M) =>
once(find(S,SS,Start,_End)).</langsyntaxhighlight>
 
{{out}}
Line 4,057 ⟶ 4,571:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Str (chop "This is a string")
(prinl (head 4 (nth Str 6))) # From 6 of 4 length
(prinl (nth Str 6)) # From 6 up to the end
Line 4,064 ⟶ 4,578:
(prinl # From "isa" of length 8
(head 8
(seek '((S) (pre? "is a" S)) Str) ) ) )</langsyntaxhighlight>
{{out}}
<pre>is a
Line 4,073 ⟶ 4,587:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
s='abcdefghijk';
n=4; m=3;
Line 4,082 ⟶ 4,596:
u=substr(s,1,length(s)-1);
u=substr(s,index(s,'g'),m);
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
Since .NET and PowerShell use zero-based indexing, all character indexes have to be reduced by one.
<langsyntaxhighlight lang="powershell"># test string
$s = "abcdefgh"
# test parameters
Line 4,108 ⟶ 4,622:
# starting from a known substring within the string and of m length
# s2 = 'cd', m = 3
$s.Substring($s.IndexOf($s2), $m) # returns 'cde'</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 4,114 ⟶ 4,628:
{{works with|SWI Prolog|7}}
 
<langsyntaxhighlight lang="prolog">
substring_task(Str, N, M, Char, SubStr) :-
sub_string(Str, N, M, _, Span),
Line 4,132 ⟶ 4,646:
sub_string(String, Before, _, _, Sub),
sub_string(String, Before, M, _, FromSubToM).
</syntaxhighlight>
</lang>
 
Running it:
 
<langsyntaxhighlight lang="prolog">
?- substring_task("abcdefghijk", 2, 4, "d", "ef").
from n to m :cdef
Line 4,144 ⟶ 4,658:
from known substring to m :efgh
true
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<lang PureBasic>If OpenConsole()
 
Define baseString.s, m, n
baseString = "Thequickbrownfoxjumpsoverthelazydog."
n = 12
m = 5
;Display the substring starting from n characters in and of m length.
PrintN(Mid(baseString, n, m))
;Display the substring starting from n characters in, up to the end of the string.
PrintN(Mid(baseString, n)) ;or PrintN(Right(baseString, Len(baseString) - n))
;Display the substring whole string minus last character
PrintN(Left(baseString, Len(baseString) - 1))
;Display the substring starting from a known character within the string and of m length.
PrintN(Mid(baseString, FindString(baseString, "b", 1), m))
 
;Display the substring starting from a known substring within the string and of m length.
PrintN(Mid(baseString, FindString(baseString, "ju", 1), m))
 
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</lang>
{{out}}
<pre>wnfox
wnfoxjumpsoverthelazydog.
Thequickbrownfoxjumpsoverthelazydog
brown
jumps</pre>
 
=={{header|Python}}==
Python uses zero-based indexing, so the n'th character is at index n-1.
 
<langsyntaxhighlight lang="python">>>> s = 'abcdefgh'
>>> n, m, char, chars = 2, 3, 'd', 'cd'
>>> # starting from n=2 characters in and m=3 in length;
Line 4,203 ⟶ 4,682:
>>> s[indx:indx+m]
'cde'
>>></langsyntaxhighlight>
 
=={{header|QB64}}==
<lang QB64>
DefStr S
DefInt I
string1 = "abcdefghijklmnopqrstuvwxyz"
substring = "klm"
Dim Achar As String * 1
Istart = 6
Ilength = 10
Achar = "c"
 
' starting from n characters in and of m length;
Print Mid$(string1, Istart, Ilength)
' starting from n characters in, up to the end of the string;
Print Mid$(string1, Istart)
Print Right$(string1, Len(string1) - Istart + 1)
' whole string minus the last character;
Print Left$(string1, Len(string1) - 1)
Print Mid$(string1, 1, Len(string1) - 1)
' starting from a known character within the string and of m length;
Print Mid$(string1, InStr(string1, Achar), Ilength)
' starting from a known substring within the string and of m length.
Print Mid$(string1, InStr(string1, substring), Ilength)
End
</lang>
=={{header|Quackery}}==
 
<code>find$</code> is defined at [[Count occurrences of a substring#Quackery]].
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "abcdefgh" ] is s ( --> $ )
[ 2 ] is n ( --> n )
[ 3 ] is m ( --> n )
Line 4,245 ⟶ 4,699:
ch s tuck find split nip m split drop echo$ cr
ss s tuck find$ split nip m split drop echo$ cr
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,256 ⟶ 4,710:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">s <- "abcdefgh"
n <- 2; m <- 2; char <- 'd'; chars <- 'cd'
substring(s, n, n + m)
Line 4,264 ⟶ 4,718:
substring(s, indx, indx + m)
indx <- which(strsplit(s, '')[[1]] %in% strsplit(chars, '')[[1]])[1]
substring(s, indx, indx + m)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 4,294 ⟶ 4,748:
(substring str (caar (regexp-match-positions (regexp-quote start-str)
str))) ; -> "xyz"
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>my $str = 'abcdefgh';
my $n = 2;
my $m = 3;
Line 4,305 ⟶ 4,759:
say $str.substr(0, *-1);
say $str.substr($str.index('d'), $m);
say $str.substr($str.index('de'), $m);</langsyntaxhighlight>
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">define println use $s
$s print "\n" print
 
Line 4,333 ⟶ 4,787:
$str $matchChrs split as $l
"" $l 0 set $l $matchChrs join
0 $subLen extract println</langsyntaxhighlight>
{{out}}
<pre>34
Line 4,345 ⟶ 4,799:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Retrieve Substring"
URL: http://rosettacode.org/wiki/Substring#REBOL
Line 4,385 ⟶ 4,839:
 
print ["Starting from substring, length m:"
copy/part find s chars m]</langsyntaxhighlight>
 
{{out}}
Line 4,398 ⟶ 4,852:
=={{header|ReScript}}==
 
<langsyntaxhighlight lang="rescript">let s = "ABCDEFGH"
let from = 2
let length = 3
Line 4,410 ⟶ 4,864:
Js.log(Js.String.substrAtMost(~from=(Js.String.indexOf("B", s)), ~length, s))
Js.log(Js.String.substrAtMost(~from=(Js.String.indexOf("BC", s)), ~length, s))
</syntaxhighlight>
</lang>
{{output}}
<pre>$ bsc substr.res > substr.js
Line 4,426 ⟶ 4,880:
=={{header|REXX}}==
Note: &nbsp; in REXX, &nbsp; the 1<sup>st</sup> character &nbsp; ''index'' &nbsp; of a string is &nbsp; '''1''', &nbsp; not &nbsp; '''0'''.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates various ways to extract substrings from a string of characters.*/
$='abcdefghijk'; n=4; m=3 /*define some constants: string, index, length of string. */
say 'original string='$ /* [↑] M can be zero (which indicates a null string).*/
Line 4,457 ⟶ 4,911:
say u
parse var $ 'def' a +(m) /*an alternate method by using the PARSE instruction. */
say a /*stick a fork in it, we're all done and Bob's your uncle.*/</langsyntaxhighlight>
'''output''' &nbsp; when using the (internal) default strings:
<pre>
Line 4,482 ⟶ 4,936:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">cStr = "a":"h" # 'abcdefgh'
n = 3 m = 3
# starting from n characters in and of m length
Line 4,494 ⟶ 4,948:
# starting from a known substring within the string and of m length
See substr(cStr,substr(cStr,"de"),m) +nl #=> def
</syntaxhighlight>
</lang>
 
=={{header|RPG}}==
<langsyntaxhighlight lang="rpg"> * 1...5....1....5....2....5..
D myString S 30 inz('Liebe bewegt das Universum!')
D output S 30 inz('')
Line 4,521 ⟶ 4,975:
output = ' *** end *** ';
dsply ' ' ' ' output;
/end-free</langsyntaxhighlight>
{{out}}
<pre>
Line 4,529 ⟶ 4,983:
DSPLY Universum
DSPLY bewegt
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! Code
! Comments
|-
|
≪ → string n m char sub ≪
string n DUP m + 1 - SUB
string n OVER SIZE SUB
string 1 OVER SIZE 1 - SUB
string DUP char POS DUP m + 1 - SUB
string DUP sub POS DUP m + 1 - SUB
≫ ≫ '''SHOWC''' STO
|
''( string start length char sub -- sub1 .. sub5 )''
from n characters in and of m length
from n characters in, up to the end of the string
whole string minus the last character
from a character within the string and of m length
from a substring within the string and of m length
|}
The following piece of code will deliver what is required:
"abcdefgh" 2 3 "d" "cd" '''SHOWC'''
{{out}}
<pre>
5: bcd
4: bcdefgh
3: abcdefg
2: def
1: cde
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">str = 'abcdefgh'
n = 2
m = 3
Line 4,541 ⟶ 5,029:
puts str[str.index('d'), m] #=> def
puts str[str.index('de'), m] #=> def
puts str[/a.*d/] #=> abcd</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<lang runbasic>n = 2
m = 3
s$ = "abcd"
a$ = mid$(a$,n,m) ' starting from n characters in and of m length
a$ = mid$(a$,n) ' starting from n characters in, up to the end of the string
a$ = Print mid$(a$,1,(len(a$)-1)) ' whole string minus last character
a$ = mid$(a$,instr(a$,s$,1),m) ' starting from a known character within the string and of m length
a$ = mid$(a$,instr(a$,s$,1), m) ' starting from a known substring within the string and of m length.</lang>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
let s = "abc文字化けdef";
let n = 2;
Line 4,575 ⟶ 5,053:
let spos = s.find("けd").unwrap();
println!("{}", s[spos..].chars().take(m).collect::<String>());
</syntaxhighlight>
</lang>
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">data _null_;
a="abracadabra";
b=substr(a,2,3); /* first number is position, starting at 1,
second number is length */
put _all_;
run;</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
s ::= "hello world shortest program";
Line 4,595 ⟶ 5,073:
#OUT + s.substring(s.search("ro"), 3) + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight lang="scala">object Substring {
// Ruler 1 2 3 4 5 6
// 012345678901234567890123456789012345678901234567890123456789012
Line 4,621 ⟶ 5,099:
// Alternatively
assert("good life is one" == str.drop(str.indexOf("good")).take(m))
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Guile}}
<langsyntaxhighlight lang="scheme">(define s "Hello, world!")
(define n 5)
(define m (+ n 6))
Line 4,642 ⟶ 5,120:
 
(display (substring s (string-contains s "lo") m))
(newline)</langsyntaxhighlight>
 
=={{header|Sed}}==
<langsyntaxhighlight lang="bash">
# 2 chars starting from 3rd
$ echo string | sed -r 's/.{3}(.{2}).*/\1/'
Line 4,657 ⟶ 5,135:
$ echo string | sed -r 's/.*(r.{2}).*/\1/'
rin
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 4,673 ⟶ 5,151:
writeln(stri[pos(stri, 'c') len M]);
writeln(stri[pos(stri, "de") len M]);
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,686 ⟶ 5,164:
=={{header|SenseTalk}}==
Note: SenseTalk indexes from 1 and ranges are inclusive
<langsyntaxhighlight lang="sensetalk">set mainString to "87654321"
set n to 3
set m to 4
Line 4,703 ⟶ 5,181:
set subOffset to offset of sub in mainString
put characters subOffset to subOffset + m - 1 of mainString
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var str = 'abcdefgh';
var n = 2;
var m = 3;
Line 4,713 ⟶ 5,191:
say str.substr(0, -1); #=> abcdefg
say str.substr(str.index('d'), m); #=> def
say str.substr(str.index('de'), m); #=> def</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">
#s := 'hello world shortest program'.
#n := 13.
Line 4,725 ⟶ 5,203:
inform: (s copyFrom: (s indexOf: $w) to: (s indexOf: $w) + m).
inform: (s copyFrom: (s indexOfSubSeq: 'ro') to: (s indexOfSubSeq: 'ro') + m).
</syntaxhighlight>
</lang>
 
=={{header|Smalltalk}}==
The distinction between searching a single character or a string into another string is rather blurred. In the following code, instead of using <tt>'w'</tt> (a string) we could use <tt>$w</tt> (a character), but it makes no difference.
 
<langsyntaxhighlight lang="smalltalk">|s|
s := 'hello world shortest program'.
 
Line 4,743 ⟶ 5,221:
to: ( ((s indexOfRegex: 'w') first) + 4) ) displayNl.
(s copyFrom: ((s indexOfRegex: 'ro') first)
to: ( ((s indexOfRegex: 'ro') first) + 2) ) displayNl.</langsyntaxhighlight>
 
These last two examples in particular seem rather complex, so
Line 4,750 ⟶ 5,228:
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">String extend [
copyFrom: index length: nChar [
^ self copyFrom: index to: ( index + nChar - 1 )
Line 4,765 ⟶ 5,243:
(s copyFrom: 13 length: 5) displayNl.
(s copyFromRegex: 'w' length: 5) displayNl.
(s copyFromRegex: 'ro' length: 3) displayNl.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang="snobol"> string = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
Line 4,783 ⟶ 5,261:
* starting from a known substring <= m within the string and of m length.
string (known_str len(m - size(known_str))) . output
end</langsyntaxhighlight>
 
{{out}}
Line 4,795 ⟶ 5,273:
{{works with|Db2 LUW}}
In Db2, there are different ways to find the position of a character or substring. For this reason, several examples are shown. Please take a look at the documentation for more details.
<langsyntaxhighlight lang="sql pl">
select 'the quick brown fox jumps over the lazy dog' from sysibm.sysdummy1;
select substr('the quick brown fox jumps over the lazy dog', 5, 15) from sysibm.sysdummy1;
Line 4,814 ⟶ 5,292:
 
select substr('the quick brown fox jumps over the lazy dog', locate('fox', 'the quick brown fox jumps over the lazy dog')) from sysibm.sysdummy1;
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,864 ⟶ 5,342:
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">s = "Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
 
usubstr(s, 25, 11)
Line 4,876 ⟶ 5,354:
 
usubstr(s, -3, .)
γῆν</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">
let string = "Hello, Swift language"
let (n, m) = (5, 4)
Line 4,937 ⟶ 5,415:
string[start..<end]
}
</syntaxhighlight>
</lang>
 
=={{header|Tailspin}}==
Tailspin doesn't really let you manipulate parts of strings. You can get a list of characters (or, really, clumps of combining characters) by <langsyntaxhighlight lang="tailspin">[$s...]</langsyntaxhighlight> and manipulate parts of that list, and recombine as <syntaxhighlight lang ="tailspin">'$a...;'</langsyntaxhighlight> if you really want to. The better Tailspin way to handle parts of strings is to use a "composer" to compose meaningful structure from the string (and discard unwanted parts).
<langsyntaxhighlight lang="tailspin">
composer substr&{from:, length:}
(<'.{$:$from-1;}'>) <'.{$length;}'> (<'.*'>)
Line 4,977 ⟶ 5,455:
'
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,988 ⟶ 5,466:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set str "abcdefgh"
set n 2
set m 3
Line 5,003 ⟶ 5,481:
# From Tcl 8.5 onwards, these can be contracted somewhat.
puts [string range [string range $str [string first "d" $str] end] $m-1]
puts [string range [string range $str [string first "de" $str] end] $m-1]</langsyntaxhighlight>
Of course, if you were doing 'position-plus-length' a lot, it would be easier to add another subcommand to <code>string</code>, like this:
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl"># Define the substring operation, efficiently
proc ::substring {string start length} {
string range $string $start [expr {$start + $length - 1}]
Line 5,024 ⟶ 5,502:
puts [string range $str 0 end-1]
puts [string substr $str [string first "d" $str] $m]
puts [string substr $str [string first "de" $str] $m]</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
string="abcdefgh", n=4,m=n+2
Line 5,041 ⟶ 5,519:
substring=EXTRACT (string,":{substring}:"|,0)
PRINT substring
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,054 ⟶ 5,532:
===POSIX shells===
{{works with|Almquist Shell}}
<langsyntaxhighlight lang="bash">str="abc qrdef qrghi"
n=6
m=3
Line 5,062 ⟶ 5,540:
printf '%s\n' "${str%?}"
expr "r${str#*r}" : "\(.\{1,$m\}\)"
expr "qr${str#*qr}" : "\(.\{1,$m\}\)"</langsyntaxhighlight>
 
<pre>def
Line 5,074 ⟶ 5,552:
===Bourne Shell===
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">str="abc qrdef qrghi"
n=6
m=3
Line 5,090 ⟶ 5,568:
}
expr "x$str" : "x.\{`index "$str" r`\}\(.\{1,$m\}\)"
expr "x$str" : "x.\{`index "$str" qr`\}\(.\{1,$m\}\)"</langsyntaxhighlight>
 
<pre>def
Line 5,101 ⟶ 5,579:
{{works with|zsh}}
Note that the last two constructs won't work with bash as only zsh supports nested string manipulation.
<langsyntaxhighlight lang="bash">
#!/bin/zsh
string='abcdefghijk'
Line 5,110 ⟶ 5,588:
echo ${${string/*c/c}:0:3} # Display 3 chars starting with 'c'
echo ${${string/*cde/cde}:0:3} # Display 3 chars starting with 'cde'
</syntaxhighlight>
</lang>
 
===Pipe===
Line 5,118 ⟶ 5,596:
{{works with|Almquist Shell}}
 
<langsyntaxhighlight lang="bash">#!/bin/sh
str=abcdefghijklmnopqrstuvwxyz
n=12
Line 5,127 ⟶ 5,605:
printf '%s\n' "${str%?}"
printf q%s "${str#*q}" | cut -c 1-$m
printf pq%s "${str#*pq}" | cut -c 1-$m</langsyntaxhighlight>
 
{{out}}
Line 5,145 ⟶ 5,623:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">
string s = "Hello, world!";
int n = 1;
Line 5,161 ⟶ 5,639:
int index_of_lo = s.index_of("lo");
string s_fromlo_for_m = s[index_of_lo:index_of_lo + m];
</syntaxhighlight>
</lang>
 
=={{header|VBAV (Vlang)}}==
{{trans|AutoHotkey}}
{{trans|Phix}}<lang vb>Public Sub substring()
1) Substring function argument in V (Vlang) uses end position versus length in AHK.
'(1) starting from n characters in and of m length;
2) V (Vlang) arrays are 0 index based.
'(2) starting from n characters in, up to the end of the string;
<syntaxhighlight lang="v (vlang)">fn main() {
'(3) whole string minus last character;
'(4) starting from a known character within the string and of m length;
'(5) starting from a known substring within the string and of m length.
sentence = "the last thing the man said was the"
n = 10: m = 5
'(1)
Debug.Print Mid(sentence, n, 5)
'(2)
Debug.Print Right(sentence, Len(sentence) - n + 1)
'(3)
Debug.Print Left(sentence, Len(sentence) - 1)
'(4)
k = InStr(1, sentence, "m")
Debug.Print Mid(sentence, k, 5)
'(5)
k = InStr(1, sentence, "aid")
Debug.Print Mid(sentence, k, 5)
End Sub</lang>{{out}}
<pre>thing
thing the man said was the
the last thing the man said was th
man s
aid w</pre>
 
=={{header|VBScript}}==
<lang vb>
s = "rosettacode.org"
 
'starting from n characters in and of m length
WScript.StdOut.WriteLine Mid(s,8,4)
 
'starting from n characters in, up to the end of the string
WScript.StdOut.WriteLine Mid(s,8,Len(s)-7)
 
'whole string minus last character
WScript.StdOut.WriteLine Mid(s,1,Len(s)-1)
 
'starting from a known character within the string and of m length
WScript.StdOut.WriteLine Mid(s,InStr(1,s,"c"),4)
 
'starting from a known substring within the string and of m length
WScript.StdOut.WriteLine Mid(s,InStr(1,s,"ose"),6)
</lang>
 
{{Out}}
<pre>
code
code.org
rosettacode.or
code
osetta
</pre>
 
=={{header|Vlang}}==
{{trans|AutoHotKey}}
Substring function argument in Vlang uses end position versus length in AHK.
<lang vlang>fn main() {
str := "abcdefghijklmnopqrstuvwxyz"
find_char := "q"
Line 5,246 ⟶ 5,666:
// starting from a known character within the string and of m length // returns nothing if not found
println(str.substr(str.index(find_string) or {return}, (str.index(find_string) or {return}) + m))
}</langsyntaxhighlight>
 
{{Out}}
Line 5,258 ⟶ 5,678:
 
=={{header|Wart}}==
<langsyntaxhighlight lang="python">s <- "abcdefgh"
s.0
=> "a"
Line 5,279 ⟶ 5,699:
# starting from a known substring within the string and of <tt>m</tt> length.
let start (pos s pat)
(s start start+m)</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "./str" for Str
var s = "αβγδεζηθ"
Line 5,309 ⟶ 5,729:
if (sx >= 0) {
System.print("Start '%(ks)', length %(m): %(Str.sub(s[sx..-1], 0...m))")
}</langsyntaxhighlight>
 
{{out}}
Line 5,323 ⟶ 5,743:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include xpllib; \provides StrLen and StrFind
 
proc PMid(S, N, M); \Print string at Nth character M chars long
Line 5,339 ⟶ 5,759:
PMid(StrFind(S, "d" ), 1, M); \starting from known char and of M length
PMid(StrFind(S, "cd"), 1, M); \starting from known substring and of M length
]</langsyntaxhighlight>
 
{{out}}
Line 5,349 ⟶ 5,769:
cde
</pre>
 
=={{header|Yabasic}}==
<lang yabasic>c$ = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
// starting from n characters in and of m length;
print mid$(c$, n, m)
// starting from n characters in, up to the end of the string;
print mid$(c$, n)
// whole string minus last character;
print left$(c$, len(c$) - 1)
// starting from a known character within the string and of m length;
print mid$(c$, instr(c$, "b"), m)
// starting from a known substring within the string and of m length.
f$ = "pq"
print mid$(c$, instr(c$, f$), m)
end</lang>
{{out}}
<pre>lmnop
lmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
bcdef
pqrst</pre>
 
=={{header|Yorick}}==
<langsyntaxhighlight lang="yorick">str = "abcdefgh";
n = 2;
m = 3;
Line 5,389 ⟶ 5,786:
// starting from a known substring within the string and of m length
match = strfind("cd", str);
write, strpart(str, [match(1), match(1)+m]);</langsyntaxhighlight>
 
=={{header|zkl}}==
8 bit ASCII
<langsyntaxhighlight lang="zkl">var str = "abcdefgh", n = 2, m = 3;
str[n,m] //-->"cde"
str[n,*] //-->"cdefgh"
str[0,-1] //-->"abcdefg"
str[str.find("d"),m] //-->"def"
str[str.find("de"),m] //-->"def"</langsyntaxhighlight>
 
 
162

edits