Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Substring
note: Basic language learning

View file

@ -0,0 +1,26 @@
{{basic data operation}}
[[Category:String manipulation]]
[[Category:Simple]]
[[Category:Strings]]
;Task:
Display a substring:
:* &nbsp; starting from &nbsp; '''<tt>n</tt>''' &nbsp; characters in and of &nbsp; '''<tt>m</tt>''' &nbsp; length;
:* &nbsp; starting from &nbsp; '''<tt>n'''</tt> &nbsp; characters in, &nbsp; up to the end of the string;
:* &nbsp; whole string minus the last character;
:* &nbsp; starting from a known &nbsp; character &nbsp; within the string and of &nbsp; '''<tt>m</tt>''' &nbsp; length;
:* &nbsp; starting from a known &nbsp; substring &nbsp; within the string and of &nbsp; '''<tt>m</tt>''' &nbsp; length.
<br>
If the program uses UTF-8 or UTF-16, &nbsp; it must work on any valid Unicode code point,
whether in the &nbsp; [https://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane Basic Multilingual Plane] &nbsp; or above it.
The program must reference logical characters (code points), &nbsp; not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
{{Template:Strings}}
<br><br>

View file

@ -0,0 +1,10 @@
V s = abcdefgh
V n = 2
V m = 3
V char = d
V chars = cd
print(s[n - 1 .+ m]) // starting from n=2 characters in and m=3 in length
print(s[n - 1 ..]) // starting from n characters in, up to the end of the string
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

View file

@ -0,0 +1,290 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program subString64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessString: .asciz "Result : "
szString1: .asciz "abcdefghijklmnopqrstuvwxyz"
szStringStart: .asciz "abcdefg"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
szSubString: .skip 500 // buffer result
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszString1 // address input string
ldr x1,qAdrszSubString // address output string
mov x2,22 // location
mov x3,4 // length
bl subStringNbChar // starting from n characters in and of m length
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszSubString // display substring result
bl affichageMess
ldr x0,qAdrszCarriageReturn // display line return
bl affichageMess
//
ldr x0,qAdrszString1
ldr x1,qAdrszSubString
mov x2,15 // location
bl subStringEnd //starting from n characters in, up to the end of the string
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszSubString
bl affichageMess
ldr x0,qAdrszCarriageReturn // display line return
bl affichageMess
//
ldr x0,qAdrszString1
ldr x1,qAdrszSubString
bl subStringMinus // whole string minus last character
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszSubString
bl affichageMess
ldr x0,qAdrszCarriageReturn // display line return
bl affichageMess
//
ldr x0,qAdrszString1
ldr x1,qAdrszSubString
mov x2,'c' // start character
mov x3,5 // length
bl subStringStChar //starting from a known character within the string and of m length
cmp x0,-1 // error ?
beq 2f
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszSubString
bl affichageMess
ldr x0,qAdrszCarriageReturn // display line return
bl affichageMess
//
2:
ldr x0,qAdrszString1
ldr x1,qAdrszSubString
ldr x2,qAdrszStringStart // sub string to start
mov x3,10 // length
bl subStringStString // starting from a known substring within the string and of m length
cmp x0,-1 // error ?
beq 3f
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszSubString
bl affichageMess
ldr x0,qAdrszCarriageReturn // display line return
bl affichageMess
3:
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessString: .quad szMessString
qAdrszString1: .quad szString1
qAdrszSubString: .quad szSubString
qAdrszStringStart: .quad szStringStart
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* sub strings index start number of characters */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of the output string */
/* x2 contains the start index */
/* x3 contains numbers of characters to extract */
/* x0 returns number of characters or -1 if error */
subStringNbChar:
stp x1,lr,[sp,-16]! // save registers
mov x14,#0 // counter byte output string
1:
ldrb w15,[x0,x2] // load byte string input
cbz x15,2f // zero final ?
strb w15,[x1,x14] // store byte output string
add x2,x2,1 // increment counter
add x14,x14,1
cmp x14,x3 // end ?
blt 1b // no -> loop
2:
strb wzr,[x1,x14] // store final zero byte string 2
mov x0,x14
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* sub strings index start at end of string */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of the output string */
/* x2 contains the start index */
/* x0 returns number of characters or -1 if error */
subStringEnd:
stp x2,lr,[sp,-16]! // save registers
mov x14,0 // counter byte output string
1:
ldrb w15,[x0,x2] // load byte string 1
cbz x15,2f // zero final ?
strb w15,[x1,x14]
add x2,x2,1
add x14,x14,1
b 1b // loop
2:
strb wzr,[x1,x14] // store final zero byte string 2
mov x0,x14
100:
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* whole string minus last character */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of the output string */
/* x0 returns number of characters or -1 if error */
subStringMinus:
stp x1,lr,[sp,-16]! // save registers
mov x12,0 // counter byte input string
mov x14,0 // counter byte output string
1:
ldrb w15,[x0,x12] // load byte string
cbz x15,2f // zero final ?
strb w15,[x1,x14]
add x12,x12,1
add x14,x14,1
b 1b // loop
2:
sub x14,x14,1
strb wzr,[x1,x14] // store final zero byte string 2
mov x0,x14
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* starting from a known character within the string and of m length */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of the output string */
/* x2 contains the character */
/* x3 contains the length
/* x0 returns number of characters or -1 if error */
subStringStChar:
stp x1,lr,[sp,-16]! // save registers
mov x16,0 // counter byte input string
mov x14,0 // counter byte output string
1:
ldrb w15,[x0,x16] // load byte string
cbz x15,4f // zero final ?
cmp x15,x2 // character find ?
beq 2f // yes
add x16,x16,1 // no -> increment indice
b 1b // loop
2:
strb w15,[x1,x14]
add x16,x16,1
add x14,x14,1
cmp x14,x3
bge 3f
ldrb w15,[x0,x16] // load byte string
cbnz x15,2b // loop if no zero final
3:
strb wzr,[x1,x14] // store final zero byte string 2
mov x0,x14
b 100f
4:
strb w15,[x1,x14]
mov x0,#-1
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* starting from a known substring within the string and of m length */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of the output string */
/* x2 contains the address of string to start */
/* x3 contains the length
/* x0 returns number of characters or -1 if error */
subStringStString:
stp x1,lr,[sp,-16]! // save registers
stp x20,x21,[sp,-16]! // save registers
mov x20,x0 // save address
mov x21,x1 // save address output string
mov x1,x2
bl searchSubString
cmp x0,-1 // not found ?
beq 100f
mov x16,x0 // counter byte input string
mov x14,0
1:
ldrb w15,[x20,x16] // load byte string
strb w15,[x21,x14]
cmp x15,#0 // zero final ?
csel x0,x14,x0,eq
beq 100f
add x14,x14,1
cmp x14,x3
add x15,x16,1
csel x16,x15,x16,lt
blt 1b // loop
strb wzr,[x21,x14]
mov x0,x14 // return indice
100:
ldp x20,x21,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* search a substring in the string */
/******************************************************************/
/* x0 contains the address of the input string */
/* x1 contains the address of substring */
/* x0 returns index of substring in string or -1 if not found */
searchSubString:
stp x1,lr,[sp,-16]! // save registers
mov x12,0 // counter byte input string
mov x13,0 // counter byte string
mov x16,-1 // index found
ldrb w14,[x1,x13]
1:
ldrb w15,[x0,x12] // load byte string
cbz x15,4f // zero final ?
cmp x15,x14 // compare character
beq 2f
mov x16,-1 // no equals - > raz index
mov x13,0 // and raz counter byte
add x12,x12,1 // and increment counter byte
b 1b // and loop
2: // characters equals
cmp x16,-1 // first characters equals ?
csel x16,x12,x16,eq
// moveq x6,x2 // yes -> index begin in x6
add x13,x13,1 // increment counter substring
ldrb w14,[x1,x13] // and load next byte
cbz x14,3f // zero final ? yes -> end search
add x12,x12,1 // else increment counter string
b 1b // and loop
3:
mov x0,x16 // return indice
b 100f
4:
mov x0,#-1 // yes returns error
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

View file

@ -0,0 +1,16 @@
main: (
STRING s = "abcdefgh";
INT n = 2, m = 3;
CHAR char = "d";
STRING chars = "cd";
printf(($gl$, s[n:n+m-1]));
printf(($gl$, s[n:]));
printf(($gl$, s[:UPB s-1]));
INT pos;
char in string("d", pos, s);
printf(($gl$, s[pos:pos+m-1]));
string in string("de", pos, s);
printf(($gl$, s[pos:pos+m-1]))
)

View file

@ -0,0 +1,308 @@
/* ARM assembly Raspberry PI */
/* program substring.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BUFFERSIZE, 100
/* Initialized data */
.data
szMessString: .asciz "Result : "
szString1: .asciz "abcdefghijklmnopqrstuvwxyz"
szStringStart: .asciz "abcdefg"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
szSubString: .skip 500 @ buffer result
/* code section */
.text
.global main
main:
ldr r0,iAdrszString1 @ address input string
ldr r1,iAdrszSubString @ address output string
mov r2,#22 @ location
mov r3,#4 @ length
bl subStringNbChar @ starting from n characters in and of m length
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszSubString @ display substring result
bl affichageMess
ldr r0,iAdrszCarriageReturn @ display line return
bl affichageMess
@
ldr r0,iAdrszString1
ldr r1,iAdrszSubString
mov r2,#15 @ location
bl subStringEnd @starting from n characters in, up to the end of the string
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszSubString
bl affichageMess
ldr r0,iAdrszCarriageReturn @ display line return
bl affichageMess
@
ldr r0,iAdrszString1
ldr r1,iAdrszSubString
bl subStringMinus @ whole string minus last character
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszSubString
bl affichageMess
ldr r0,iAdrszCarriageReturn @ display line return
bl affichageMess
@
ldr r0,iAdrszString1
ldr r1,iAdrszSubString
mov r2,#'c' @ start character
mov r3,#5 @ length
bl subStringStChar @starting from a known character within the string and of m length
cmp r0,#-1 @ error ?
beq 2f
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszSubString
bl affichageMess
ldr r0,iAdrszCarriageReturn @ display line return
bl affichageMess
@
2:
ldr r0,iAdrszString1
ldr r1,iAdrszSubString
ldr r2,iAdrszStringStart @ sub string to start
mov r3,#10 @ length
bl subStringStString @ starting from a known substring within the string and of m length
cmp r0,#-1 @ error ?
beq 3f
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszSubString
bl affichageMess
ldr r0,iAdrszCarriageReturn @ display line return
bl affichageMess
3:
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessString: .int szMessString
iAdrszString1: .int szString1
iAdrszSubString: .int szSubString
iAdrszStringStart: .int szStringStart
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* sub strings index start number of characters */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of the output string */
/* r2 contains the start index */
/* r3 contains numbers of characters to extract */
/* r0 returns number of characters or -1 if error */
subStringNbChar:
push {r1-r5,lr} @ save registers
mov r4,#0 @ counter byte output string
1:
ldrb r5,[r0,r2] @ load byte string input
cmp r5,#0 @ zero final ?
beq 2f
strb r5,[r1,r4] @ store byte output string
add r2,#1 @ increment counter
add r4,#1
cmp r4,r3 @ end ?
blt 1b @ no -> loop
2:
mov r5,#0
strb r5,[r1,r4] @ load byte string 2
mov r0,r4
100:
pop {r1-r5,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* sub strings index start at end of string */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of the output string */
/* r2 contains the start index */
/* r0 returns number of characters or -1 if error */
subStringEnd:
push {r1-r5,lr} @ save registers
mov r4,#0 @ counter byte output string
1:
ldrb r5,[r0,r2] @ load byte string 1
cmp r5,#0 @ zero final ?
beq 2f
strb r5,[r1,r4]
add r2,#1
add r4,#1
b 1b @ loop
2:
mov r5,#0
strb r5,[r1,r4] @ load byte string 2
mov r0,r4
100:
pop {r1-r5,lr} @ restaur registers
bx lr
/******************************************************************/
/* whole string minus last character */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of the output string */
/* r0 returns number of characters or -1 if error */
subStringMinus:
push {r1-r5,lr} @ save registers
mov r2,#0 @ counter byte input string
mov r4,#0 @ counter byte output string
1:
ldrb r5,[r0,r2] @ load byte string
cmp r5,#0 @ zero final ?
beq 2f
strb r5,[r1,r4]
add r2,#1
add r4,#1
b 1b @ loop
2:
sub r4,#1
mov r5,#0
strb r5,[r1,r4] @ load byte string 2
mov r0,r4
100:
pop {r1-r5,lr} @ restaur registers
bx lr
/******************************************************************/
/* starting from a known character within the string and of m length */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of the output string */
/* r2 contains the character */
/* r3 contains the length
/* r0 returns number of characters or -1 if error */
subStringStChar:
push {r1-r5,lr} @ save registers
mov r6,#0 @ counter byte input string
mov r4,#0 @ counter byte output string
1:
ldrb r5,[r0,r6] @ load byte string
cmp r5,#0 @ zero final ?
streqb r5,[r1,r4]
moveq r0,#-1
beq 100f
cmp r5,r2
beq 2f
add r6,#1
b 1b @ loop
2:
strb r5,[r1,r4]
add r6,#1
add r4,#1
cmp r4,r3
bge 3f
ldrb r5,[r0,r6] @ load byte string
cmp r5,#0
bne 2b
3:
mov r5,#0
strb r5,[r1,r4] @ load byte string 2
mov r0,r4
100:
pop {r1-r5,lr} @ restaur registers
bx lr
/******************************************************************/
/* starting from a known substring within the string and of m length */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of the output string */
/* r2 contains the address of string to start */
/* r3 contains the length
/* r0 returns number of characters or -1 if error */
subStringStString:
push {r1-r8,lr} @ save registers
mov r7,r0 @ save address
mov r8,r1 @ counter byte string
mov r1,r2
bl searchSubString
cmp r0,#-1
beq 100f
mov r6,r0 @ counter byte input string
mov r4,#0
1:
ldrb r5,[r7,r6] @ load byte string
strb r5,[r8,r4]
cmp r5,#0 @ zero final ?
moveq r0,r4
beq 100f
add r4,#1
cmp r4,r3
addlt r6,#1
blt 1b @ loop
mov r5,#0
strb r5,[r8,r4]
mov r0,r4
100:
pop {r1-r8,lr} @ restaur registers
bx lr
/******************************************************************/
/* search a substring in the string */
/******************************************************************/
/* r0 contains the address of the input string */
/* r1 contains the address of substring */
/* r0 returns index of substring in string or -1 if not found */
searchSubString:
push {r1-r6,lr} @ save registers
mov r2,#0 @ counter byte input string
mov r3,#0 @ counter byte string
mov r6,#-1 @ index found
ldrb r4,[r1,r3]
1:
ldrb r5,[r0,r2] @ load byte string
cmp r5,#0 @ zero final ?
moveq r0,#-1 @ yes returns error
beq 100f
cmp r5,r4 @ compare character
beq 2f
mov r6,#-1 @ no equals - > raz index
mov r3,#0 @ and raz counter byte
add r2,#1 @ and increment counter byte
b 1b @ and loop
2: @ characters equals
cmp r6,#-1 @ first characters equals ?
moveq r6,r2 @ yes -> index begin in r6
add r3,#1 @ increment counter substring
ldrb r4,[r1,r3] @ and load next byte
cmp r4,#0 @ zero final ?
beq 3f @ yes -> end search
add r2,#1 @ else increment counter string
b 1b @ and loop
3:
mov r0,r6
100:
pop {r1-r6,lr} @ restaur registers
bx lr
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return

View file

@ -0,0 +1,33 @@
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

View file

@ -0,0 +1,11 @@
BEGIN {
str = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
print substr(str, n, m)
print substr(str, n)
print substr(str, 1, length(str) - 1)
print substr(str, index(str, "q"), m)
print substr(str, index(str, "pq"), m)
}

View file

@ -0,0 +1,73 @@
BYTE FUNC FindC(CHAR ARRAY text CHAR c)
BYTE i
i=1
WHILE i<=text(0)
DO
IF text(i)=c THEN
RETURN (i)
FI
i==+1
OD
RETURN (0)
BYTE FUNC FindS(CHAR ARRAY text,sub)
BYTE i,j,found
i=1
WHILE i<=text(0)-sub(0)+1
DO
found=0
FOR j=1 TO sub(0)
DO
IF text(i+j-1)#sub(j) THEN
found=0 EXIT
ELSE
found=1
FI
OD
IF found THEN
RETURN (i)
FI
i==+1
OD
RETURN (0)
PROC Main()
CHAR ARRAY text="qwertyuiop"
CHAR ARRAY sub="tyu"
CHAR ARRAY res(20)
BYTE n,m
CHAR c
PrintF("Original string:%E ""%S""%E%E",text)
n=3 m=5
SCopyS(res,text,n,n+m-1)
PrintF("Substring start from %B and length %B:%E ""%S""%E%E",n,m,res)
n=4
SCopyS(res,text,n,text(0))
PrintF("Substring start from %B up to the end:%E ""%S""%E%E",n,res)
SCopyS(res,text,1,text(0)-1)
PrintF("Whole string without the last char:%E ""%S""%E%E",res)
c='w m=4
n=FindC(text,c)
IF n=0 THEN
PrintF("Character '%C' not found in string%E%E",c)
ELSE
SCopyS(res,text,n,n+m-1)
PrintF("Substring start from '%C' and len %B:%E ""%S""%E%E",c,m,res)
FI
n=FindS(text,sub)
m=6
IF n=0 THEN
PrintF("String ""%S"" not found in string%E%E",sub)
ELSE
SCopyS(res,text,n,n+m-1)
PrintF("Substring start from '%S' and len %B: ""%S""%E%E",sub,m,res)
FI
RETURN

View file

@ -0,0 +1 @@
type String is array (Positive range <>) of Character;

View file

@ -0,0 +1 @@
A (<first-index>..<last-index>)

View file

@ -0,0 +1,14 @@
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure Test_Slices is
Str : constant String := "abcdefgh";
N : constant := 2;
M : constant := 3;
begin
Put_Line (Str (Str'First + N - 1..Str'First + N + M - 2));
Put_Line (Str (Str'First + N - 1..Str'Last));
Put_Line (Str (Str'First..Str'Last - 1));
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;

View file

@ -0,0 +1,12 @@
const str = "abcdefg"
var n = 2
var m = 3
println (str[n:n+m-1]) // pos 2 length 3
println (str[n:]) // pos 2 to end
println (str >> 1) // remove last character
var p = find (str, 'c')
println (str[p:p+m-1]) // from pos of p length 3
var s = find (str, "bc")
println (str[s, s+m-1]) // pos of bc length 3

View file

@ -0,0 +1,18 @@
text s;
data b, d;
s = "The quick brown fox jumps over the lazy dog.";
o_text(cut(s, 4, 15));
o_newline();
o_text(cut(s, 4, length(s)));
o_newline();
o_text(delete(s, -1));
o_newline();
o_text(cut(s, index(s, 'q'), 5));
o_newline();
b_cast(b, s);
b_cast(d, "brown");
o_text(cut(s, b_find(b, d), 15));
o_newline();

View file

@ -0,0 +1,15 @@
String x = 'testing123';
//Test1: testing123
System.debug('Test1: ' + x.substring(0,x.length()));
//Test2: esting123
System.debug('Test2: ' + x.substring(1,x.length()));
//Test3: testing123
System.debug('Test3: ' + x.substring(0));
//Test4: 3
System.debug('Test4: ' + x.substring(x.length()-1));
//Test5:
System.debug('Test5: ' + x.substring(1,1));
//Test 6: testing123
System.debug('Test6: ' + x.substring(x.indexOf('testing')));
//Test7: e
System.debug('Test7: ' + x.substring(1,2));

View file

@ -0,0 +1,103 @@
-- SUBSTRINGS -----------------------------------------------------------------
-- take :: Int -> Text -> Text
on take(n, s)
text 1 thru n of s
end take
-- drop :: Int -> Text -> Text
on drop(n, s)
text (n + 1) thru -1 of s
end drop
-- breakOn :: Text -> Text -> (Text, Text)
on breakOn(strPattern, s)
set {dlm, my text item delimiters} to {my text item delimiters, strPattern}
set lstParts to text items of s
set my text item delimiters to dlm
{item 1 of lstParts, strPattern & (item 2 of lstParts)}
end breakOn
-- init :: Text -> Text
on init(s)
if length of s > 0 then
text 1 thru -2 of s
else
missing value
end if
end init
-- TEST -----------------------------------------------------------------------
on run
set str to "一二三四五六七八九十"
set legends to {¬
"from n in, of n length", ¬
"from n in, up to end", ¬
"all but last", ¬
"from matching char, of m length", ¬
"from matching string, of m length"}
set parts to {¬
take(3, drop(4, str)), ¬
drop(3, str), ¬
init(str), ¬
take(3, item 2 of breakOn("五", str)), ¬
take(4, item 2 of breakOn("六七", str))}
script tabulate
property strPad : " "
on |λ|(l, r)
l & drop(length of l, strPad) & r
end |λ|
end script
linefeed & intercalate(linefeed, ¬
zipWith(tabulate, ¬
legends, parts)) & linefeed
end run
-- GENERIC FUNCTIONS FOR TEST -------------------------------------------------
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith

View file

@ -0,0 +1,19 @@
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;
1 PRINT MID$(S$,N,M)
REM starting from n characters in, up to the end of the string;
2 PRINT RIGHT$(S$,L-N+1)
REM whole string minus the last character;
3 PRINT LEFT$(S$,L-1)
REM starting from a known character within the string and of m length;
4 READ F$ :GOSUB 6
REM starting from a known substring within the string and of m length.
5 READ F$
6 FOR I = 1 TO L : IF MID$(S$,I,LEN(F$)) = F$ THEN PRINT MID$(S$,I,M) : RETURN
7 NEXT : RETURN

View file

@ -0,0 +1,20 @@
str: "abcdefgh"
n: 2
m: 3
; starting from n=2 characters in and m=3 in length
print slice str n-1 n+m-2
; starting from n characters in, up to the end of the string
print slice str n-1 (size str)-1
; whole string minus last character
print slice str 0 (size str)-2
; starting from a known character char="d"
; within the string and of m length
print slice str index str "d" m+(index str "d")-1
; 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

View file

@ -0,0 +1,34 @@
String := "abcdefghijklmnopqrstuvwxyz"
; also: String = abcdefghijklmnopqrstuvwxyz
n := 12
m := 5
; starting from n characters in and of m length;
subString := SubStr(String, n, m)
; alternative: StringMid, subString, String, n, m
MsgBox % subString
; starting from n characters in, up to the end of the string;
subString := SubStr(String, n)
; alternative: StringMid, subString, String, n
MsgBox % subString
; whole string minus last character;
StringTrimRight, subString, String, 1
; alternatives: subString := SubStr(String, 1, StrLen(String) - 1)
; StringMid, subString, String, 1, StrLen(String) - 1
MsgBox % subString
; starting from a known character within the string and of m length;
findChar := "q"
subString := SubStr(String, InStr(String, findChar), m)
; alternatives: RegExMatch(String, findChar . ".{" . m - 1 . "}", subString)
; StringMid, subString, String, InStr(String, findChar), m
MsgBox % subString
; starting from a known character within the string and of m length;
findString := "pq"
subString := SubStr(String, InStr(String, findString), m)
; alternatives: RegExMatch(String, findString . ".{" . m - StrLen(findString) . "}", subString)
; StringMid, subString, String, InStr(String, findString), m
MsgBox % subString

View file

@ -0,0 +1,19 @@
Lbl SUB1
0→{r₁+r₂+r₃}
r₁+r₂
Return
Lbl SUB2
r₁+r₂
Return
Lbl SUB3
0→{r₁+length(r₁)-1}
r₁
Return
Lbl SUB4
inData(r₂,r₁)-1→I
0→{r₁+I+r₃}
r₁+I
Return

View file

@ -0,0 +1,15 @@
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, length(c$))
# whole string minus last character;
print left(c$, length(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

View file

@ -0,0 +1,25 @@
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$

View file

@ -0,0 +1,10 @@
53"Marshmallow"
"shmal"
3"Marshmallow"
"shmallow"
¯1"Marshmallow"
"Marshmallo"
(/'m'=)"Marshmallow"
"mallow"
(/"sh")"Marshmallow"
"shmallow"

View file

@ -0,0 +1,27 @@
( (basestring = "The five boxing wizards jump quickly")
& (n = 10)
& (m = 5)
{ starting from n characters in and of m length: }
& @(!basestring:? [(!n+-1) ?substring [(!n+!m+-1) ?)
& out$!substring
{ starting from n characters in, up to the end of the string: }
& @(!basestring:? [(!n+-1) ?substring)
& out$!substring
{ whole string minus last character: }
& @(!basestring:?substring [-2 ?)
& out$!substring
{ starting from a known character within the string and of m length: }
& (char = "w")
& @(!basestring:? ([?p !char ?: ?substring [(!p+!m) ?))
& out$!substring
{ starting from a known substring within the string and of m length: }
& (find = "iz")
& @(!basestring:? ([?p !find ?: ?substring [(!p+!m) ?))
& out$!substring
&
)

View file

@ -0,0 +1,12 @@
blsq ) "RosettaCode"5.+
"Roset"
blsq ) "RosettaCode"5.+2.-
"set"
blsq ) "RosettaCode""set"ss
2
blsq ) "RosettaCode"J"set"ss.-
"settaCode"
blsq ) "RosettaCode"~]
"RosettaCod"
blsq ) "RosettaCode"[-
"osettaCode"

View file

@ -0,0 +1,4 @@
blsq ) "RosettaCode"{0 1 3 5}si
"Roet"
blsq ) "RosettaCode"{0 1 3 5}di
"oetaCde"

View file

@ -0,0 +1,18 @@
#include <iostream>
#include <string>
int main()
{
std::string s = "0123456789";
int const n = 3;
int const m = 4;
char const c = '2';
std::string const sub = "456";
std::cout << s.substr(n, m)<< "\n";
std::cout << s.substr(n) << "\n";
std::cout << s.substr(0, s.size()-1) << "\n";
std::cout << s.substr(s.find(c), m) << "\n";
std::cout << s.substr(s.find(sub), m) << "\n";
}

View file

@ -0,0 +1,26 @@
using System;
namespace SubString
{
class Program
{
static void Main(string[] args)
{
string s = "0123456789";
const int n = 3;
const int m = 2;
const char c = '3';
const string z = "345";
// A: starting from n characters in and of m length;
Console.WriteLine(s.Substring(n, m));
// B: starting from n characters in, up to the end of the string;
Console.WriteLine(s.Substring(n, s.Length - n));
// C: whole string minus the last character;
Console.WriteLine(s.Substring(0, s.Length - 1));
// D: starting from a known character within the string and of m length;
Console.WriteLine(s.Substring(s.IndexOf(c), m));
// E: starting from a known substring within the string and of m length.
Console.WriteLine(s.Substring(s.IndexOf(z), m));
}
}
}

View file

@ -0,0 +1,4 @@
// 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]);

View file

@ -0,0 +1,52 @@
/*
* RosettaCode: Substring, C89
*
* In this 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 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.
*
* This example program DOES NOT make substrings. The program simply displays
* certain parts of the input string.
*
*/
#define _CRT_SECURE_NO_WARNINGS /* MSVS compilers need this */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Put no more than m characters from string to standard output.
*
* It is worth noting that printf("%*s",width,string) does not limit the number
* of characters to be printed.
*
* @param string null terminated string
* @param m number of characters to display
*/
void putm(char* string, size_t m)
{
while(*string && m--)
putchar(*string++);
}
int main(void)
{
char string[] =
"Programs for other encodings (such as 8-bit ASCII, or EUC-JP)."
int n = 3;
int m = 4;
char knownCharacter = '(';
char knownSubstring[] = "encodings";
putm(string+n-1, m ); putchar('\n');
puts(string+n+1); putchar('\n');
putm(string, strlen(string)-1); putchar('\n');
putm(strchr(string, knownCharacter), m ); putchar('\n');
putm(strstr(string, knownSubstring), m ); putchar('\n');
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,56 @@
/*
* RosettaCode: Substring, C89, Unicode
*
* In this 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 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.
*
* This example program DOES NOT make substrings. The program simply displays
* certain parts of the input string.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Put all characters from string to standard output AND write newline.
* BTW, _putws may not be avaliable.
*/
void put(wchar_t* string)
{
while(*string)
putwchar(*string++);
putwchar(L'\n');
}
/*
* Put no more than m characters from string to standard output AND newline.
*/
void putm(wchar_t* string, size_t m)
{
while(*string && m--)
putwchar(*string++);
putwchar(L'\n');
}
int main(void)
{
wchar_t string[] =
L"Programs for other encodings (such as 8-bit ASCII).";
int n = 3;
int m = 4;
wchar_t knownCharacter = L'(';
wchar_t knownSubstring[] = L"encodings";
putm(string+n-1,m);
put (string+n+1);
putm(string, wcslen(string)-1);
putm(wcschr(string, knownCharacter), m );
putm(wcsstr(string, knownSubstring), m );
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,74 @@
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *substring(const char *s, size_t n, ptrdiff_t m)
{
char *result;
/* check for null s */
if (NULL == s)
return NULL;
/* negative m to mean 'up to the mth char from right' */
if (m < 0)
m = strlen(s) + m - n + 1;
/* n < 0 or m < 0 is invalid */
if (n < 0 || m < 0)
return NULL;
/* make sure string does not end before n
* and advance the "s" pointer to beginning of substring */
for ( ; n > 0; s++, n--)
if (*s == '\0')
/* string ends before n: invalid */
return NULL;
result = malloc(m+1);
if (NULL == result)
/* memory allocation failed */
return NULL;
result[0]=0;
strncat(result, s, m); /* strncat() will automatically add null terminator
* if string ends early or after reading m characters */
return result;
}
char *str_wholeless1(const char *s)
{
return substring(s, 0, strlen(s) - 1);
}
char *str_fromch(const char *s, int ch, ptrdiff_t m)
{
return substring(s, strchr(s, ch) - s, m);
}
char *str_fromstr(const char *s, char *in, ptrdiff_t m)
{
return substring(s, strstr(s, in) - s , m);
}
#define TEST(A) do { \
char *r = (A); \
if (NULL == r) \
puts("--error--"); \
else { \
puts(r); \
free(r); \
} \
} while(0)
int main()
{
const char *s = "hello world shortest program";
TEST( substring(s, 12, 5) ); // get "short"
TEST( substring(s, 6, -1) ); // get "world shortest program"
TEST( str_wholeless1(s) ); // "... progra"
TEST( str_fromch(s, 'w', 5) ); // "world"
TEST( str_fromstr(s, "ro", 3) ); // "rog"
return 0;
}

View file

@ -0,0 +1,56 @@
identification division.
program-id. substring.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 original.
05 value "this is a string".
01 starting pic 99 value 3.
01 width pic 99 value 8.
01 pos pic 99.
01 ender pic 99.
01 looking pic 99.
01 indicator pic x.
88 found value high-value when set to false is low-value.
01 look-for pic x(8).
procedure division.
substring-main.
display "Original |" original "|, n = " starting " m = " width
display original(starting : width)
display original(starting :)
display original(1 : length(original) - 1)
move "a" to look-for
move 1 to looking
perform find-position
if found
display original(pos : width)
end-if
move "is a st" to look-for
move length(trim(look-for)) to looking
perform find-position
if found
display original(pos : width)
end-if
goback.
find-position.
set found to false
compute ender = length(original) - looking
perform varying pos from 1 by 1 until pos > ender
if original(pos : looking) equal look-for then
set found to true
exit perform
end-if
end-perform
.
end program substring.

View file

@ -0,0 +1,22 @@
(def string "alphabet")
(def n 2)
(def m 4)
(def len (count string))
;starting from n characters in and of m length;
(println
(subs string n (+ n m))) ;phab
;starting from n characters in, up to the end of the string;
(println
(subs string n)) ;phabet
;whole string minus last character;
(println
(subs string 0 (dec len))) ;alphabe
;starting from a known character within the string and of m length;
(let [pos (.indexOf string (int \l))]
(println
(subs string pos (+ pos m)))) ;lpha
;starting from a known substring within the string and of m length.
(let [pos (.indexOf string "ph")]
(println
(subs string pos (+ pos m)))) ;phab

View file

@ -0,0 +1,22 @@
<cfoutput>
<cfset str = "abcdefg">
<cfset n = 2>
<cfset m = 3>
<!--- Note: In CF index starts at 1 rather than 0
starting from n characters in and of m length --->
#mid( str, n, m )#
<!--- starting from n characters in, up to the end of the string --->
<cfset countFromRight = Len( str ) - n + 1>
#right( str, countFromRight )#
<!--- whole string minus last character --->
<cfset allButLast = Len( str ) - 1>
#left( str, allButLast )#
<!--- starting from a known character within the string and of m length --->
<cfset startingIndex = find( "b", str )>
#mid( str, startingIndex, m )#
<!--- starting from a known substring within the string and of m length --->
<cfset startingIndexSubString = find( "bc", str )>
#mid( str, startingIndexSubString, m )#
</cfoutput>

View file

@ -0,0 +1,21 @@
<cfscript>
str="abcdefg";
n = 2;
m = 3;
// Note: In CF index starts at 1 rather than 0
// starting from n characters in and of m length
writeOutput( mid( str, n, m ) );
// starting from n characters in, up to the end of the string
countFromRight = Len( str ) - n + 1;
writeOutput( right( str, countFromRight ) );
// whole string minus last character
allButLast = Len( str ) - 1;
writeOutput( left( str, allButLast ) );
// starting from a known character within the string and of m length
startingIndex = find( "b", str );
writeOutput( mid( str, startingIndex, m ) );
// starting from a known substring within the string and of m length
startingIndexSubString = find( "bc", str );
writeOutput( mid( str, startingIndexSubString, m ) );
</cfscript>

View file

@ -0,0 +1,30 @@
10 REM SUBSTRING ... ROSETTACODE.ORG
20 A$ = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
30 X$ = "J" : S$ = "FOX"
40 N = 5: M = 11
50 PRINT "THE STRING:"
60 PRINT A$
70 PRINT
80 PRINT "SUBSTRING STARTING FROM" N "CHARACTERS IN AND OF" M "LENGTH:"
90 PRINT MID$(A$,N,M)
100 PRINT
110 PRINT "STARTING FROM" N "CHARACTERS IN, UP TO THE END OF THE STRING:"
120 PRINT RIGHT$(A$,LEN(A$)+1-N)
130 PRINT
140 PRINT "WHOLE STRING MINUS LAST CHARACTER:"
150 PRINT LEFT$(A$,LEN(A$)-1)
160 PRINT
170 PRINT "STARTING FROM '";X$;"' AND OF" M "LENGTH:"
180 I = 1
190 IF MID$(A$,I,1)=X$ THEN 220
200 I = I+1
210 GOTO 190
220 PRINT RIGHT$(A$,LEN(A$)+1-I)
230 PRINT
240 PRINT "STARTING FROM '";S$;"' AND OF" M "LENGTH:"
250 I = 1
260 IF MID$(A$,I,LEN(S$))=S$ THEN 290
270 I = I+1
280 GOTO 260
290 PRINT RIGHT$(A$,LEN(A$)+1-I)
300 END

View file

@ -0,0 +1,12 @@
(let ((string "0123456789")
(n 2)
(m 3)
(start #\5)
(substring "34"))
(list (subseq string n (+ n m))
(subseq string n)
(subseq string 0 (1- (length string)))
(let ((pos (position start string)))
(subseq string pos (+ pos m)))
(let ((pos (search substring string)))
(subseq string pos (+ pos m)))))

View file

@ -0,0 +1,25 @@
MODULE Substrings;
IMPORT StdLog,Strings;
PROCEDURE Do*;
CONST
aStr = "abcdefghijklmnopqrstuvwxyz";
VAR
str: ARRAY 128 OF CHAR;
pos: INTEGER;
BEGIN
Strings.Extract(aStr,3,10,str);
StdLog.String("from 3, 10 characters:> ");StdLog.String(str);StdLog.Ln;
Strings.Extract(aStr,3,LEN(aStr) - 3,str);
StdLog.String("from 3, until the end:> ");StdLog.String(str);StdLog.Ln;
Strings.Extract(aStr,0,LEN(aStr) - 1,str);
StdLog.String("whole string but last:> ");StdLog.String(str);StdLog.Ln;
Strings.Find(aStr,'d',0,pos);
Strings.Extract(aStr,pos + 1,10,str);
StdLog.String("from 'd', 10 characters:> ");StdLog.String(str);StdLog.Ln;
Strings.Find(aStr,"de",0,pos);
Strings.Extract(aStr,pos + LEN("de"),10,str);
StdLog.String("from 'de', 10 characters:> ");StdLog.String(str);StdLog.Ln;
END Do;
END Substrings.

View file

@ -0,0 +1,17 @@
def substring_demo(string, n, m, known_character, known_substring)
n -= 1
puts string[n...n+m]
puts string[n...]
puts string.rchop
known_character_index = string.index(known_character).not_nil!
puts string[known_character_index...known_character_index+m]
known_substring_index = string.index(known_substring).not_nil!
puts string[known_substring_index...known_substring_index+m]
end
substring_demo("crystalline", 3, 5, 't', "st")

View file

@ -0,0 +1,18 @@
import std.stdio, std.string;
void main() {
const s = "the quick brown fox jumps over the lazy dog";
enum n = 5, m = 3;
writeln(s[n .. n + m]);
writeln(s[n .. $]);
writeln(s[0 .. $ - 1]);
const i = s.indexOf("q");
writeln(s[i .. i + m]);
const j = s.indexOf("qu");
writeln(s[j .. j + m]);
}

View file

@ -0,0 +1,12 @@
;starting from n characters in and of m length;
SUB_STR = STR(n:m)
;starting from n characters in, up to the end of the string;
SUB_STR = STR(n,$LEN(STR))
;whole string minus last character;
SUB_STR = STR(1,%TRIM(STR)-1)
;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)

View file

@ -0,0 +1,19 @@
program ShowSubstring;
{$APPTYPE CONSOLE}
uses SysUtils;
const
s = '0123456789';
n = 3;
m = 4;
c = '2';
sub = '456';
begin
Writeln(Copy(s, n, m)); // starting from n characters in and of m length;
Writeln(Copy(s, n, Length(s))); // starting from n characters in, up to the end of the string;
Writeln(Copy(s, 1, Length(s) - 1)); // whole string minus last character;
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.

View file

@ -0,0 +1,16 @@
let s = "0123456789"
let n = 3
let m = 2
let c = '3'
let z = "345"
// A: starting from n characters in and of m length;
print(s.Substring(n, m))
// B: starting from n characters in, up to the end of the string;
print(s[n..])
// C: whole string minus the last character;
print(s[..-1])
// D: starting from a known character within the string and of m length;
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))

View file

@ -0,0 +1,8 @@
def string := "aardvarks"
def n := 4
def m := 4
println(string(n, n + m))
println(string(n))
println(string(0, string.size() - 1))
println({string(def i := string.indexOf1('d'), i + m)})
println({string(def i := string.startOf("ard"), i + m)})

View file

@ -0,0 +1,32 @@
/* In this task display a 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.
*/
IMPORT STD; //imports a standard string library
TheString := 'abcdefghij';
CharIn := 3; //n
StrLength := 4; //m
KnownChar := 'f';
KnownSub := 'def';
FindKnownChar := STD.Str.Find(TheString, KnownChar,1);
FindKnownSub := STD.Str.Find(TheString, KnownSub,1);
OUTPUT(TheString[Charin..CharIn+StrLength-1]); //task1
OUTPUT(TheString[Charin..]); //task2
OUTPUT(TheString[1..LENGTH(TheString)-1]); //task3
OUTPUT(TheString[FindKnownChar..FindKnownChar+StrLength-1]);//task4
OUTPUT(TheString[FindKnownSub..FindKnownSub+StrLength-1]); //task5
/* OUTPUTS:
defg
cdefghij
abcdefghi
fghi
defg
*/

View file

@ -0,0 +1,3 @@
a$ = "2019-05-22 22:54:22"
print substr a$ 12 5
print substr a$ 12 -1

View file

@ -0,0 +1,13 @@
#import <Foundation/Foundation.h>
int main()
autoreleasepool
str := 'abcdefgh'
n := 2
m := 3
Log( '%@', str[0 .. str.length-1] ) // abcdefgh
Log( '%@', str[n .. m] ) // cd
Log( '%@', str[n .. str.length-1] ) // cdefgh
Log( '%@', str.substringFromIndex: n ) // cdefgh
Log( '%@', str[(str.rangeOfString:'b').location .. m] ) // bcd
return 0

View file

@ -0,0 +1,61 @@
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

View file

@ -0,0 +1,16 @@
import extensions;
public program()
{
var s := "0123456789";
var n := 3;
var m := 2;
var c := $51;
var z := "345";
console.writeLine(s.Substring(n, m));
console.writeLine(s.Substring(n, s.Length - n));
console.writeLine(s.Substring(0, s.Length - 1));
console.writeLine(s.Substring(s.indexOf(0, c), m));
console.writeLine(s.Substring(s.indexOf(0, z), m))
}

View file

@ -0,0 +1,12 @@
s = "abcdefgh"
String.slice(s, 2, 3) #=> "cde"
String.slice(s, 1..3) #=> "bcd"
String.slice(s, -3, 2) #=> "fg"
String.slice(s, 3..-1) #=> "defgh"
# UTF-8
s = "αβγδεζηθ"
String.slice(s, 2, 3) #=> "γδε"
String.slice(s, 1..3) #=> "βγδ"
String.slice(s, -3, 2) #=> "ζη"
String.slice(s, 3..-1) #=> "δεζηθ"

View file

@ -0,0 +1,39 @@
sequence baseString, subString, findString
integer findChar
integer m, n
baseString = "abcdefghijklmnopqrstuvwxyz"
-- starting from n characters in and of m length;
n = 12
m = 5
subString = baseString[n..n+m-1]
puts(1, subString )
puts(1,'\n')
-- starting from n characters in, up to the end of the string;
n = 12
subString = baseString[n..$]
puts(1, subString )
puts(1,'\n')
-- whole string minus last character;
subString = baseString[1..$-1]
puts(1, subString )
puts(1,'\n')
-- starting from a known character within the string and of m length;
findChar = 'o'
m = 5
n = find(findChar,baseString)
subString = baseString[n..n+m-1]
puts(1, subString )
puts(1,'\n')
-- starting from a known substring within the string and of m length.
findString = "pq"
m = 5
n = match(findString,baseString)
subString = baseString[n..n+m-1]
puts(1, subString )
puts(1,'\n')

View file

@ -0,0 +1,13 @@
[<EntryPoint>]
let main args =
let s = ""
let n, m = 3, 2
let c = ''
let z = ""
printfn "%s" (s.Substring(n, m))
printfn "%s" (s.Substring(n))
printfn "%s" (s.Substring(0, s.Length - 1))
printfn "%s" (s.Substring(s.IndexOf(c), m))
printfn "%s" (s.Substring(s.IndexOf(z), m))
0

View file

@ -0,0 +1,20 @@
USING: math sequences kernel ;
! starting from n characters in and of m length
: subseq* ( from length seq -- newseq ) [ over + ] dip subseq ;
! starting from n characters in, up to the end of the string
: dummy ( seq n -- tailseq ) tail ;
! whole string minus last character
: dummy1 ( seq -- headseq ) but-last ;
USING: fry sequences kernel ;
! helper word
: subseq-from-* ( subseq len seq quot -- seq ) [ nip ] prepose 2keep subseq* ; inline
! starting from a known character within the string and of m length;
: subseq-from-char ( char len seq -- seq ) [ index ] subseq-from-* ;
! starting from a known substring within the string and of m length.
: subseq-from-seq ( subseq len seq -- seq ) [ start ] subseq-from-* ;

View file

@ -0,0 +1,13 @@
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
s = "FalconPL is not just a multi-paradign language but also fun"
n = 12
m = 5
> "starting from n characters in and of m length: ", s[n:n+m]
> "starting from n characters in, up to the end of the string: ", s[n:]
> "whole string minus last character: ", s[0:len(s)-1]
new_n = s.find("j", 0)
> "starting from a known character within the string and of m length: ", s[new_n:new_n+m]
new_n = s.find("mu", 0)
> "starting from a known character within the string and of m length: ", s[new_n:new_n+m]

View file

@ -0,0 +1,9 @@
2 constant Pos
3 constant Len
: Str ( -- c-addr u ) s" abcdefgh" ;
Str Pos /string drop Len type \ cde
Str Pos /string type \ cdefgh
Str 1- type \ abcdefg
Str char d scan drop Len type \ def
Str s" de" search 2drop Len type \ def

View file

@ -0,0 +1,24 @@
program test_substring
character (*), parameter :: string = 'The quick brown fox jumps over the lazy dog.'
character (*), parameter :: substring = 'brown'
character , parameter :: c = 'q'
integer , parameter :: n = 5
integer , parameter :: m = 15
integer :: i
! Display the substring starting from n characters in and of length m.
write (*, '(a)') string (n : n + m - 1)
! Display the substring starting from n characters in, up to the end of the string.
write (*, '(a)') string (n :)
! Display the whole string minus the last character.
i = len (string) - 1
write (*, '(a)') string (: i)
! Display the substring starting from a known character and of length m.
i = index (string, c)
write (*, '(a)') string (i : i + m - 1)
! Display the substring starting from a known substring and of length m.
i = index (string, substring)
write (*, '(a)') string (i : i + m - 1)
end program test_substring

View file

@ -0,0 +1,5 @@
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]

View file

@ -0,0 +1,12 @@
' 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

View file

@ -0,0 +1,12 @@
test = "🐱abcdefg😾"
n = 3
m = 2
println[substrLen[test, n, m]]
println[right[test, -m]]
println[left[test, -1]]
pos = indexOf["c"]
if pos != -1
println[substrLen[test, pos, m]]
pos = indexOf[test, "cd"]
if pos != -1
println[substrLen[test, pos, m]]

View file

@ -0,0 +1,21 @@
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

View file

@ -0,0 +1,4 @@
LETTERS;
# "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
LETTERS{[5 .. 10]};
# "EFGHIJ"

View file

@ -0,0 +1,10 @@
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

View file

@ -0,0 +1,26 @@
package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
// for reference
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
// starting from n characters in and of m length
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
// starting from n characters in, up to the end of the string
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
// whole string minus last character
fmt.Printf("All but last: %s\n", s[:len(s)-1])
// starting from a known character within the string and of m length
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
// starting from a known substring within the string and of m length
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}

View file

@ -0,0 +1,29 @@
package main
import (
"fmt"
"strings"
)
func main() {
s := "αβγδεζηθ"
r := []rune(s)
n, m := 2, 3
kc := 'δ' // known character
ks := "δε" // known string
// for reference
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
// starting from n characters in and of m length
fmt.Printf("Start %d, length %d: %s\n", n, m, string(r[n:n+m]))
// starting from n characters in, up to the end of the string
fmt.Printf("Start %d, to end: %s\n", n, string(r[n:]))
// whole string minus last character
fmt.Printf("All but last: %s\n", string(r[:len(r)-1]))
// starting from a known character within the string and of m length
dx := strings.IndexRune(s, kc)
fmt.Printf("Start %q, length %d: %s\n", kc, m, string([]rune(s[dx:])[:m]))
// starting from a known substring within the string and of m length
sx := strings.Index(s, ks)
fmt.Printf("Start %q, length %d: %s\n", ks, m, string([]rune(s[sx:])[:m]))
}

View file

@ -0,0 +1,21 @@
def str = 'abcdefgh'
def n = 2
def m = 3
// #1
println str[n..n+m-1]
/* or */
println str[n..<(n+m)]
// #2
println str[n..-1]
// #3
println str[0..-2]
// #4
def index1 = str.indexOf('d')
println str[index1..index1+m-1]
/* or */
println str[index1..<(index1+m)]
// #5
def index2 = str.indexOf('de')
println str[index2..index2+m-1]
/* or */
println str[index2..<(index2+m)]

View file

@ -0,0 +1,3 @@
t45 n c s | null sub = []
| otherwise = take n. head $ sub
where sub = filter(isPrefixOf c) $ tails s

View file

@ -0,0 +1,31 @@
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T (Text, take, drop, init, breakOn)
import qualified Data.Text.IO as O (putStrLn)
fromMforN :: Int -> Int -> T.Text -> T.Text
fromMforN n m s = T.take m (T.drop n s)
fromNtoEnd :: Int -> T.Text -> T.Text
fromNtoEnd = T.drop
allButLast :: T.Text -> T.Text
allButLast = T.init
fromCharForN, fromStringForN :: Int -> T.Text -> T.Text -> T.Text
fromCharForN m needle haystack = T.take m $ snd $ T.breakOn needle haystack
fromStringForN = fromCharForN
-- TEST ---------------------------------------------------
main :: IO ()
main =
mapM_
O.putStrLn
([ fromMforN 9 10
, fromNtoEnd 20
, allButLast
, fromCharForN 6 ""
, fromStringForN 6 "大势"
] <*>
["天地不仁仁者人也🐒话说天下大势分久必合🍑合久必分🔥"])

View file

@ -0,0 +1,12 @@
CHARACTER :: string = 'ABCDEFGHIJK', known = 'B', substring = 'CDE'
REAL, PARAMETER :: n = 5, m = 8
WRITE(Messagebox) string(n : n + m - 1), "| substring starting from n, length m"
WRITE(Messagebox) string(n :), "| substring starting from n, to end of string"
WRITE(Messagebox) string(1: LEN(string)-1), "| whole string minus last character"
pos_known = INDEX(string, known)
WRITE(Messagebox) string(pos_known : pos_known+m-1), "| substring starting from pos_known, length m"
pos_substring = INDEX(string, substring)
WRITE(Messagebox) string(pos_substring : pos_substring+m-1), "| substring starting from pos_substring, length m"

View file

@ -0,0 +1,9 @@
100 LET A$="abcdefghijklmnopqrstuvwxyz"
110 LET N=10:LET M=7
120 PRINT A$(N:N+M-1)
130 PRINT A$(N:)
140 PRINT A$(:LEN(A$)-1)
150 LET I=POS(A$,"g")
160 PRINT A$(I:I+M-1)
170 LET I=POS(A$,"ijk")
180 PRINT A$(I:I+M-1)

View file

@ -0,0 +1,14 @@
procedure main(arglist)
write("Usage: substring <string> <first position> <second position> <single character> <substring>")
s := \arglist[1] | "aardvarks"
n := \arglist[2] | 5
m := \arglist[3] | 4
c := \arglist[4] | "d"
ss := \arglist[5] | "ard"
write( s[n+:m] )
write( s[n:0] )
write( s[1:-1] )
write( s[find(c,s)+:m] )
write( s[find(ss,s)+:m] )
end

View file

@ -0,0 +1,12 @@
5{.3}.'Marshmallow'
shmal
3}.'Marshmallow'
shmallow
}.'Marshmallow'
arshmallow
}:'Marshmallow'
Marshmallo
5{.(}.~ i.&'m')'Marshmallow'
mallo
5{.(}.~ I.@E.~&'sh')'Marshmallow'
shmal

View file

@ -0,0 +1,2 @@
'Marshmallow'{~(+i.)/3 5
shmal

View file

@ -0,0 +1,2 @@
(,.3 5)];.0 'Marshmallow'
shmal

View file

@ -0,0 +1,7 @@
require 'strings'
'sh' dropto 'Marshmallow'
shmallow
5{. 'sh' dropto 'Marshmallow'
shmal
'sh' takeafter 'Marshmallow'
mallow

View file

@ -0,0 +1,4 @@
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

View file

@ -0,0 +1,15 @@
public static String Substring(String str, int n, int m){
return str.substring(n, n+m);
}
public static String Substring(String str, int n){
return str.substring(n);
}
public static String Substring(String str){
return str.substring(0, str.length()-1);
}
public static String Substring(String str, char c, int m){
return str.substring(str.indexOf(c), str.indexOf(c)+m+1);
}
public static String Substring(String str, String sub, int m){
return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);
}

View file

@ -0,0 +1,20 @@
var str = "abcdefgh";
var n = 2;
var m = 3;
// * starting from n characters in and of m length;
str.substr(n, m); // => "cde"
// * starting from n characters in, up to the end of the string;
str.substr(n); // => "cdefgh"
str.substring(n); // => "cdefgh"
// * whole string minus last character;
str.substring(0, str.length - 1); // => "abcdefg"
// * starting from a known character within the string and of m length;
str.substr(str.indexOf('b'), m); // => "bcd"
// * starting from a known substring within the string and of m length.
str.substr(str.indexOf('bc'), m); // => "bcd"

View file

@ -0,0 +1,57 @@
(function () {
'use strict';
// take :: Int -> Text -> Text
function take(n, s) {
return s.substr(0, n);
}
// drop :: Int -> Text -> Text
function drop(n, s) {
return s.substr(n);
}
// init :: Text -> Text
function init(s) {
var n = s.length;
return (n > 0 ? s.substr(0, n - 1) : undefined);
}
// breakOn :: Text -> Text -> (Text, Text)
function breakOn(strPattern, s) {
var i = s.indexOf(strPattern);
return i === -1 ? [strPattern, ''] : [s.substr(0, i), s.substr(i)];
}
var str = '一二三四五六七八九十';
return JSON.stringify({
'from n in, of m length': (function (n, m) {
return take(m, drop(n, str));
})(4, 3),
'from n in, up to end' :(function (n) {
return drop(n, str);
})(3),
'all but last' : init(str),
'from matching char, of m length' : (function (pattern, s, n) {
return take(n, breakOn(pattern, s)[1]);
})('五', str, 3),
'from matching string, of m length':(function (pattern, s, n) {
return take(n, breakOn(pattern, s)[1]);
})('六七', str, 4)
}, null, 2);
})();

View file

@ -0,0 +1,7 @@
{
"from n in, of m length": "五六七",
"from n in, up to end": "四五六七八九十",
"all but last": "一二三四五六七八九",
"from matching char, of m length": "五六七",
"from matching string, of m length": "六七八九"
}

View file

@ -0,0 +1 @@
def s: "一二三四五六七八九十";

View file

@ -0,0 +1 @@
def ix(s): explode | index(s|explode);

View file

@ -0,0 +1,20 @@
# starting from n characters in and of m length: .[n+1: n+m+1]
"s[1:2] => \( s[1:2] )",
# starting from n characters in, up to the end of the string: .[n+1:]
"s[9:] => \( s[9:] )",
# whole string minus last character: .[0:length-1]
"s|.[0:length-1] => \(s | .[0:length-1] )",
# starting from a known character within the string and of m length:
# jq 1.4: ix(c) as $i | .[ $i: $i + m]
# jq>1.4: match(c).offset as $i | .[ $i: $i + m]
"s | ix(\"五\") as $i | .[$i: $i + 1] => \(s | ix("五") as $i | .[$i: $i + 1] )",
# starting from a known substring within the string and of m length:
# jq 1.4: ix(sub) as $i | .[ $i: $i + m]
# 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] )"

View file

@ -0,0 +1,6 @@
$ 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] => 五六

View file

@ -0,0 +1,88 @@
#!/usr/local/bin/jsish -u %s
var str = "abcdefgh";
var n = 2;
var m = 3;
// In jsish, semi-colon first character lines are echoed with result
;str;
;n;
;m;
// * starting from n characters in and of m length;
;str.substr(n, m);
// * starting from n characters in, up to the end of the string;
;str.substr(n);
;str.substring(n);
// * whole string minus last character;
;str.substring(0, str.length - 1);
// * starting from a known character within the string and of m length;
;str.substr(str.indexOf('b'), m);
// * starting from a known substring within the string and of m length.
;str.substr(str.indexOf('bc'), m);
/* Functional */
var res = (function () {
'use strict';
// take :: Int -> Text -> Text
function take(n, s) {
return s.substr(0, n);
}
// drop :: Int -> Text -> Text
function drop(n, s) {
return s.substr(n);
}
// init :: Text -> Text
function init(s) {
var n = s.length;
return (n > 0 ? s.substr(0, n - 1) : undefined);
}
// breakOn :: Text -> Text -> (Text, Text)
function breakOn(strPattern, s) {
var i = s.indexOf(strPattern);
return i === -1 ? [strPattern, ''] : [s.substr(0, i), s.substr(i)];
}
var str = 'abcdefgh';
return JSON.stringify({
'from 4 in, of 3 length': (function (n, m) {
return take(m, drop(n, str));
})(4, 3),
'from 3 in, up to end' : (function (n) {
return drop(n, str);
})(3),
'all but last' : init(str),
'from matching b, of length 3' : (function (pattern, s, n) {
return take(n, breakOn(pattern, s)[1]);
})('b', str, 3),
'from matching bc, of length 4':(function (pattern, s, n) {
return take(n, breakOn(pattern, s)[1]);
})('bc', str, 4)
}, true);
})();
;res;

View file

@ -0,0 +1,103 @@
#!/usr/local/bin/jsish -u %s
var str = "abcdefgh";
var n = 2;
var m = 3;
// In jsish, semi-colon first character lines are echoed with result
;str;
;n;
;m;
// * starting from n characters in and of m length;
;str.substr(n, m);
// * starting from n characters in, up to the end of the string;
;str.substr(n);
;str.substring(n);
// * whole string minus last character;
;str.substring(0, str.length - 1);
// * starting from a known character within the string and of m length;
;str.substr(str.indexOf('b'), m);
// * starting from a known substring within the string and of m length.
;str.substr(str.indexOf('bc'), m);
/* Functional */
var res = (function () {
'use strict';
// take :: Int -> Text -> Text
function take(n, s) {
return s.substr(0, n);
}
// drop :: Int -> Text -> Text
function drop(n, s) {
return s.substr(n);
}
// init :: Text -> Text
function init(s) {
var n = s.length;
return (n > 0 ? s.substr(0, n - 1) : undefined);
}
// breakOn :: Text -> Text -> (Text, Text)
function breakOn(strPattern, s) {
var i = s.indexOf(strPattern);
return i === -1 ? [strPattern, ''] : [s.substr(0, i), s.substr(i)];
}
var str = 'abcdefgh';
return JSON.stringify({
'from 4 in, of length 3': (function (n, m) {
return take(m, drop(n, str));
})(4, 3),
'from 3 in, up to end' : (function (n) {
return drop(n, str);
})(3),
'all but last' : init(str),
'from matching b, of length 3' : (function (pattern, s, n) {
return take(n, breakOn(pattern, s)[1]);
})('b', str, 3),
'from matching bc, of length 4':(function (pattern, s, n) {
return take(n, breakOn(pattern, s)[1]);
})('bc', str, 4)
}, true);
})();
;res;
/*
=!EXPECTSTART!=
str ==> abcdefgh
n ==> 2
m ==> 3
str.substr(n, m) ==> cde
str.substr(n) ==> cdefgh
str.substring(n) ==> cdefgh
str.substring(0, str.length - 1) ==> abcdefgh
str.substr(str.indexOf('b'), m) ==> bcd
str.substr(str.indexOf('bc'), m) ==> bcd
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!=
*/

View file

@ -0,0 +1,23 @@
julia> s = "abcdefg"
"abcdefg"
julia> n = 3
3
julia> s[n:end]
"cdefg"
julia> m=2
2
julia> s[n:n+m]
"cde"
julia> s[1:end-1]
"abcdef"
julia> s[search(s,'c')]
'c'
julia> s[search(s,'c'):search(s,'c')+m]
"cde"

View file

@ -0,0 +1,17 @@
// version 1.0.6
fun main(args: Array<String>) {
val s = "0123456789"
val n = 3
val m = 4
val c = '5'
val z = "12"
var i: Int
println(s.substring(n, n + m))
println(s.substring(n))
println(s.dropLast(1))
i = s.indexOf(c)
println(s.substring(i, i + m))
i = s.indexOf(z)
println(s.substring(i, i + m))
}

View file

@ -0,0 +1,58 @@
#!/bin/ksh
# 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.
# # Variables:
#
str='solve this task according to the task description,'
integer n=6 m=14
ch='v'
substr='acc'
# # Functions:
#
# # Function _length(str, start, length) - return substr from start,
# # length chars long (length=-1 = end-of-str)
#
function _length {
typeset _str ; _str="$1"
typeset _st ; integer _st=$2
typeset _ln ; integer _ln=$3
(( _ln == -1 )) && echo "${_str:${_st}}"
echo "${_str:${_st}:${_ln}}"
}
######
# main #
######
print -- "--String (Length: ${#str} chars):"
print "${str}\n"
print -- "--From char ${n} and ${m} chars in length:"
_length "${str}" ${n} ${m}
echo
print -- "--From char ${n} to the end:"
_length "${str}" ${n} -1
print -- "--Last character removed:" # Strings in ksh are zero based
_length "${str}" 0 $(( ${#str}-1 ))
echo
print -- "-From char:'${ch}' and ${m} chars in length:"
foo=${str%${ch}*}
_length "${str}" ${#foo} ${m}
echo
print -- "-From substr:'${substr}' and ${m} chars in length:"
foo=${str%${substr}*}
_length "${str}" ${#foo} ${m}
echo

View file

@ -0,0 +1,18 @@
> (set n 3)
3
> (set m 5)
5
> (string:sub_string "abcdefghijklm" n)
"cdefghijklm"
> (string:sub_string "abcdefghijklm" n (+ n m -1))
"cdefg"
> (string:sub_string "abcdefghijklm" 1 (- (length "abcdefghijklm") 1))
"abcdefghijkl"
> (set char-index (string:chr "abcdefghijklm" #\e))
5
> (string:sub_string "abcdefghijklm" char-index (+ char-index m -1))
"efghi"
> (set start-str (string:str "abcdefghijklm" "efg"))
5
> (string:sub_string "abcdefghijklm" start-str (+ start-str m -1))
"efghi"

View file

@ -0,0 +1,4 @@
{S.slice 1 2 hello brave new world}
-> brave new
{W.slice 4 11 www.rosetta.org}
-> rosetta

View file

@ -0,0 +1,23 @@
$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

View file

@ -0,0 +1,20 @@
: 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* ;
: comb "" split ; : concat "" join ; : empty? length 0= ; : tail over lensize |a,b> subscript ;
: lensize length nip ; : while do 'dup dip 'execute 2dip rot if dup 2dip else break then loop 2drop ;
: <substr> comb -rot over + |a,b> subscript concat ;
: str-tail tail concat ;
: str-index
: 2streq 2dup over lensize iota subscript eq '* reduce ;
swap 'comb bi@ length -rot 0 -rot
"2dup 'lensize bi@ <="
"2streq if 0 reshape else '1+ 2dip 0 extract drop then"
while empty? if 2drop tuck == if drop -1 then else 4 ndrop -1 then ;
'abcdefgh 'str set 2 'n set 3 'm set
n m str <substr>
str comb n str-tail
str "d" str-index m str <substr>
str "de" str-index m str <substr>

View file

@ -0,0 +1,16 @@
local(str = 'The quick grey rhino jumped over the lazy green fox.')
//starting from n characters in and of m length;
#str->substring(16,5) //rhino
//starting from n characters in, up to the end of the string
#str->substring(16) //rhino jumped over the lazy green fox.
//whole string minus last character
#str->substring(1,#str->size - 1) //The quick grey rhino jumped over the lazy green fox
//starting from a known character within the string and of m length;
#str->substring(#str->find('g'),10) //grey rhino
//starting from a known substring within the string and of m length
#str->substring(#str->find('rhino'),12) //rhino jumped

View file

@ -0,0 +1,22 @@
'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)

View file

@ -0,0 +1,30 @@
str = "The quick brown fox jumps over the lazy dog"
-- starting from n characters in and of m length
n = 5
m = 11
put str.char[n..n+m-1]
-- "quick brown"
-- starting from n characters in, up to the end of the string
n = 11
put str.char[n..str.length]
-- "brown fox jumps over the lazy dog"
-- whole string minus last character
put str.char[1..str.length-1]
-- "The quick brown fox jumps over the lazy do"
-- starting from a known character within the string and of m length
c = "x"
m = 7
pos = offset(c, str)
put str.char[pos..pos+m-1]
-- "x jumps"
-- starting from a known substring within the string and of m length
sub = "fox"
m = 9
pos = offset(sub, str)
put str.char[pos..pos+m-1]
-- "fox jumps"

View file

@ -0,0 +1,6 @@
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

View file

@ -0,0 +1,38 @@
to items :n :thing
if :n >= count :thing [output :thing]
output items :n butlast :thing
end
to butitems :n :thing
if or :n <= 0 empty? :thing [output :thing]
output butitems :n-1 butfirst :thing
end
to middle :n :m :thing
output items :m-(:n-1) butitems :n-1 :thing
end
to lastitems :n :thing
if :n >= count :thing [output :thing]
output lastitems :n butfirst :thing
end
to starts.with :sub :thing
if empty? :sub [output "true]
if empty? :thing [output "false]
if not equal? first :sub first :thing [output "false]
output starts.with butfirst :sub butfirst :thing
end
to members :sub :thing
output cascade [starts.with :sub ?] [bf ?] :thing
end
; note: Logo indices start at one
make "s "abcdefgh
print items 3 butitems 2 :s ; cde
print middle 3 5 :s ; cde
print butitems 2 :s ; cdefgh
print butlast :s ; abcdefg
print items 3 member "d :s ; def
print items 3 members "de :s ; def

View file

@ -0,0 +1,21 @@
:- object(substring).
:- public(test/5).
test(String, N, M, Character, Substring) :-
sub_atom(String, N, M, _, Substring1),
write(Substring1), nl,
sub_atom(String, N, _, 0, Substring2),
write(Substring2), nl,
sub_atom(String, 0, _, 1, Substring3),
write(Substring3), nl,
% there can be multiple occurences of the character
once(sub_atom(String, Before4, 1, _, Character)),
sub_atom(String, Before4, M, _, Substring4),
write(Substring4), nl,
% there can be multiple occurences of the substring
once(sub_atom(String, Before5, _, _, Substring)),
sub_atom(String, Before5, M, _, Substring5),
write(Substring5), nl.
:- end_object.

View file

@ -0,0 +1,7 @@
| ?- ?- substring::test('abcdefgh', 2, 3, 'b', 'bc').
cde
cdefgh
abcdefg
bcd
bcd
yes

Some files were not shown because too many files have changed in this diff Show more