void main() {
    import std.stdio;
    import std.algorithm: startsWith, endsWith, find, countUntil;

    "abcd".startsWith("ab").writeln;      // true
    "abcd".endsWith("zn").writeln;        // false
    "abab".find("bb").writeln;            // empty array (no match)
    "abcd".find("bc").writeln;            // "bcd" (substring start
                                           //        at match)
    "abab".countUntil("bb").writeln;      // -1 (no match)
    "abab".countUntil("ba").writeln;      //  1 (index of 1st match)

    // std.algorithm.startsWith also works on arrays and ranges:
    [1, 2, 3].countUntil(3).writeln;      //  2
    [1, 2, 3].countUntil([2, 3]).writeln; //  1
}


$ first_string = p1
$ length_of_first_string = f$length( first_string )
$ second_string = p2
$ length_of_second_string = f$length( second_string )
$ offset = f$locate( second_string, first_string )
$ if offset .eq. 0
$ then
$  write sys$output "first string starts with second string"
$ else
$  write sys$output "first string does not start with second string"
$ endif
$ if offset .ne. length_of_first_string
$ then
$  write sys$output "first string contains the second string at location ", offset
$ else
$  write sys$output "first string does not contain the second string at any location"
$ endif
$ temp = f$extract( length_of_first_string - length_of_second_string, length_of_second_string, first_string )
$ if second_string .eqs. temp
$ then
$  write sys$output "first string ends with the second string"
$ else
$  write sys$output "first string does not end with the second string"
$ endif


const std = @import("std");

pub fn main() !void {
    const string: []const u8 = "Hello, world!";
    const cnt_codepts_utf8 = try std.unicode.utf8CountCodepoints(string);
    // There is no sane and portable extended ascii, so the best
    // we get is counting the bytes and assume regular ascii.
    const cnt_bytes_utf8 = string.len;
    const stdout_wr = std.io.getStdOut().writer();
    try stdout_wr.print("codepoints = {d}, bytes = {d}\n", .{ cnt_codepts_utf8, cnt_bytes_utf8 });
    // TODO utf16
}


program CharacterMatching;

{$APPTYPE CONSOLE}

uses StrUtils;

begin
  WriteLn(AnsiStartsText('ab', 'abcd')); // True
  WriteLn(AnsiEndsText('zn', 'abcd')); // False
  WriteLn(AnsiContainsText('abcd', 'bb')); // False
  Writeln(AnsiContainsText('abcd', 'ab')); // True
  WriteLn(Pos('ab', 'abcd')); // 1
end.


var value = "abcd".StartsWith("ab")
value = "abcd".EndsWith("zn") //returns false
value = "abab".Contains("bb") //returns false
value = "abab".Contains("ab") //returns true
var loc = "abab".IndexOf("bb") //returns -1
loc = "abab".IndexOf("ab") //returns 0


def f(string1, string2) {
    println(string1.startsWith(string2))

    var index := 0
    while ((index := string1.startOf(string2, index)) != -1) {
        println(`at $index`)
        index += 1
    }

    println(string1.endsWith(string2))
}


(string-suffix? "nette" "Antoinette") → #t
(string-prefix? "Simon" "Simon & Garfunkel") → #t

(string-match "Antoinette" "net") → #t ;; contains
(string-index "net" "Antoinette") → 5  ;; substring location


import extensions;

public program()
{
    var s := "abcd";

    console.printLine(s," starts with ab: ",s.startingWith:"ab");
    console.printLine(s," starts with cd: ",s.startingWith:"cd");

    console.printLine(s," ends with ab: ",s.endingWith:"ab");
    console.printLine(s," ends with cd: ",s.endingWith:"cd");

    console.printLine(s," contains ab: ",s.containing:"ab");
    console.printLine(s," contains bc: ",s.containing:"bc");
    console.printLine(s," contains cd: ",s.containing:"cd");
    console.printLine(s," contains az: ",s.containing:"az");

    console.printLine(s," index of az: ",s.indexOf(0, "az"));
    console.printLine(s," index of cd: ",s.indexOf(0, "cd"));
    console.printLine(s," index of bc: ",s.indexOf(0, "bc"));
    console.printLine(s," index of ab: ",s.indexOf(0, "ab"));

    console.readChar()
}


s1 = "abcd"
s2 = "adab"
s3 = "ab"

String.starts_with?(s1, s3)
# => true
String.starts_with?(s2, s3)
# => false

String.contains?(s1, s3)
# => true
String.contains?(s2, s3)
# => true

String.ends_with?(s1, s3)
# => false
String.ends_with?(s2, s3)
# => true

# Optional requirements:
Regex.run(~r/#{s3}/, s1, return: :index)
# => [{0, 2}]
Regex.run(~r/#{s3}/, s2, return: :index)
# => [{2, 2}]

Regex.scan(~r/#{s3}/, "abcabc", return: :index)
# => [[{0, 2}], [{3, 2}]]


(defun string-contains (needle haystack)
  (string-match (regexp-quote needle) haystack))

(string-prefix-p "before" "before center after") ;=> t
(string-contains "before" "before center after") ;=> 0
(string-suffix-p "before" "before center after") ;=> nil

(string-prefix-p "center" "before center after") ;=> nil
(string-contains "center" "before center after") ;=> 7
(string-suffix-p "center" "before center after") ;=> nil

(string-prefix-p "after" "before center after") ;=> nil
(string-contains "after" "before center after") ;=> 14
(string-suffix-p "after" "before center after") ;=> t


-module(character_matching).
-export([starts_with/2,ends_with/2,contains/2]).

%% Both starts_with and ends_with are mappings to 'lists:prefix/2' and
%% 'lists:suffix/2', respectively.

starts_with(S1,S2) ->
    lists:prefix(S2,S1).

ends_with(S1,S2) ->
    lists:suffix(S2,S1).

contains(S1,S2) ->
    contains(S1,S2,1,[]).

%% While S1 is at least as long as S2 we check if S2 is its prefix,
%% storing the result if it is. When S1 is shorter than S2, we return
%% the result. NB: this will work on any arbitrary list in erlang
%% since it makes no distinction between strings and lists.
contains([_|T]=S1,S2,N,Acc) when length(S2) =< length(S1) ->
    case starts_with(S1,S2) of
        true ->
            contains(T,S2,N+1,[N|Acc]);
        false ->
            contains(T,S2,N+1,Acc)
    end;
contains(_S1,_S2,_N,Acc) ->
    Acc.


sequence first, second
integer x

first = "qwertyuiop"

-- Determining if the first string starts with second string
second = "qwerty"
if match(second, first) = 1 then
    printf(1, "'%s' starts with '%s'\n", {first, second})
else
    printf(1, "'%s' does not start with '%s'\n", {first, second})
end if

-- Determining if the first string contains the second string at any location
-- Print the location of the match for part 2
second = "wert"
x = match(second, first)
if x then
    printf(1, "'%s' contains '%s' at position %d\n", {first, second, x})
else
    printf(1, "'%s' does not contain '%s'\n", {first, second})
end if

-- Determining if the first string ends with the second string
second = "uio"
if length(second)<=length(first) and match_from(second, first, length(first)-length(second)+1) then
    printf(1, "'%s' ends with '%s'\n", {first, second})
else
    printf(1, "'%s' does not end with '%s'\n", {first, second})
end if


[<EntryPoint>]
let main args =

    let text = "一二三四五六七八九十"
    let starts = "一二"
    let ends = "九十"
    let contains = "五六"
    let notContains = "百"

    printfn "text = %A" text
    printfn "starts with %A: %A" starts (text.StartsWith(starts))
    printfn "starts with %A: %A" ends (text.StartsWith(ends))
    printfn "ends with %A: %A" ends (text.EndsWith(ends))
    printfn "ends with %A: %A" starts (text.EndsWith(starts))
    printfn "contains %A: %A" contains (text.Contains(contains))
    printfn "contains %A: %A" notContains (text.Contains(notContains))
    printfn "substring %A begins at position %d (zero-based)" contains (text.IndexOf(contains))
    let text2 = text + text
    printfn "text = %A" text2
    Seq.unfold (fun (n : int) ->
            let idx = text2.IndexOf(contains, n)
            if idx < 0 then None else Some (idx, idx+1)) 0
    |> Seq.iter (printfn "substring %A begins at position %d (zero-based)" contains)
    0


/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */

s1 = "Naig Ialocin Olracnaig"
s2 = "Naig"

var = s1.startsWith(s2) ? s1 + " starts with " + s2 : s1 + " does not start with " + s2
> var

s2 = "loc"
var = s2 in s1 ? @ "$s1 contains $s2" : @ "$s1 does not contain $s2"
> var

> s1.endsWith(s2) ? @ "s1 ends with $s2" : @ "$s1 does not end with $s2"


class Main
{
  public static Void main ()
  {
    string := "Fantom Language"
    echo ("String is: " + string)
    echo ("does string start with 'Fantom'? " + string.startsWith("Fantom"))
    echo ("does string start with 'Language'? " + string.startsWith("Language"))
    echo ("does string contain 'age'? " + string.contains("age"))
    echo ("does string contain 'page'? " + string.contains("page"))
    echo ("does string end with 'Fantom'? " + string.endsWith("Fantom"))
    echo ("does string end with 'Language'? " + string.endsWith("Language"))

    echo ("Location of 'age' is: " + string.index("age"))
    posn := string.index ("an")
    echo ("First location of 'an' is: " + posn)
    posn = string.index ("an", posn+1)
    echo ("Second location of 'an' is: " + posn)
    posn = string.index ("an", posn+1)
    if (posn == null) echo ("No third location of 'an'")
  }
}


#APPTYPE CONSOLE

DIM s = "roko, mat jane do"

IF LEFT(s, 4) = "roko" THEN PRINT STRENC(s), " starts with ", STRENC("roko")
IF INSTR(s, "mat") THEN PRINT STRENC(s), " contains ", STRENC("mat"), " at ", INSTR
IF RIGHT(s, 2) = "do" THEN PRINT STRENC(s), " ends with ", STRENC("do")
PRINT STRENC(s), " contains ", STRENC("o"), " at the following locations:", InstrEx(s, "o")

PAUSE

SUB InstrEx(mane, match)
    INSTR = 0
    WHILE INSTR(mane, match, INSTR + 1): PRINT " ", INSTR;: WEND
END SUB


: starts-with ( a l a2 l2 -- ? )
  tuck 2>r min 2r> compare 0= ;
: ends-with ( a l a2 l2 -- ? )
  tuck 2>r negate over + 0 max /string 2r> compare 0= ;
\ use SEARCH ( a l a2 l2 -- a3 l3 ? ) for contains


      SUBROUTINE STARTS(A,B)	!Text A starts with text B?
       CHARACTER*(*) A,B
        IF (INDEX(A,B).EQ.1) THEN	!Searches A to find B.
          WRITE (6,*) ">",A,"< starts with >",B,"<"
         ELSE
          WRITE (6,*) ">",A,"< does not start with >",B,"<"
        END IF
      END SUBROUTINE STARTS

      SUBROUTINE HAS(A,B)	!Text B appears somewhere in text A?
       CHARACTER*(*) A,B
       INTEGER L
        L = INDEX(A,B)		!The first position in A where B matches.
        IF (L.LE.0) THEN
          WRITE (6,*) ">",A,"< does not contain >",B,"<"
         ELSE
          WRITE (6,*) ">",A,"< contains a >",B,"<, offset",L
        END IF
      END SUBROUTINE HAS

      SUBROUTINE ENDS(A,B)	!Text A ends with text B.
       CHARACTER*(*) A,B
       INTEGER L
        L = LEN(A) - LEN(B)	!Find the tail end of A that B might match.
        IF (L.LT.0) THEN	!Dare not use an OR, because of full evaluation risks.
          WRITE (6,*) ">",A,"< is too short to end with >",B,"<"	!Might as well have a special message.
        ELSE IF (A(L + 1:L + LEN(B)).NE.B) THEN	!Otherwise, it is safe to look.
          WRITE (6,*) ">",A,"< does not end with >",B,"<"
        ELSE
          WRITE (6,*) ">",A,"< ends with >",B,"<"
        END IF
      END SUBROUTINE ENDS

      CALL STARTS("This","is")
      CALL STARTS("Theory","The")
      CALL HAS("Bananas","an")
      CALL ENDS("Banana","an")
      CALL ENDS("Banana","na")
      CALL ENDS("Brief","Much longer")
      END


' FB 1.05.0 Win64

Dim As String s1 = "abracadabra"
Dim As String s2 = "abra"
Print "First string  : "; s1
Print "Second string : "; s2
Print
Print "First string begins with second string : "; CBool(s2 = Left(s1, Len(s2)))
Dim As Integer i1 = Instr(s1, s2)
Dim As Integer i2
Print "First string contains second string    : ";
If i1 Then
  Print "at index"; i1;
  i2 = Instr(i1 + Len(s2), s1, s2)
  If i2 Then
    Print " and at index"; i2
  Else
    Print
  End If
Else
  Print "false";
End If
Print "First string ends with second string   : "; CBool(s2 = Right(s1, Len(s2)))
Print
Print "Press any key to quit"
Sleep


Public Sub Main()
Dim sString1 As String = "Hello world"
Dim sString2 As String = "Hello"

Print sString1 Begins Left(sString2, 5)                             'Determine if the first string starts with second string
If InStr(sString1, sString2) Then Print "True" Else Print "False"   'Determine if the first string contains the second string at any location
Print sString1 Ends Left(sString2, 5)                               'Determine if the first string ends with the second string

End


#define charMatch
{
    first = "qwertyuiop";

    // Determining if the first string starts with second string
    second = "qwerty";
    if (string_pos(second, first) > 0) {
        show_message("'" + first + "' starts with '" + second + "'");
    } else {
        show_message("'" + first + "' does not start with '" + second + "'");
    }

    second = "wert"
    // Determining if the first string contains the second string at any location
    // Print the location of the match for part 2
    if (string_pos(second, first) > 0) {
        show_message("'" + first + "' contains '" + second + "' at position " + string(x));
    } else {
        show_message("'" + first + "' does not contain '" + second + "'");
    }
    // Handle multiple occurrences of a string for part 2.
    x = string_count(second, first);
    show_message("'" + first + "' contains " + string(x) + " instances of '" + second + "'");

// Determining if the first string ends with the second string
    second = "random garbage"
    temp = string_copy(first,
                       (string_length(first) - string_length(second)) + 1,
                       string_length(second));
    if (temp == second) {
        show_message("'" + first + "' ends with '" + second + "'");
    } else {
        show_message("'" + first + "' does not end with '" + second + "'");
    }
}


package main

import (
    "fmt"
    "strings"
)

func match(first, second string) {
    fmt.Printf("1. %s starts with %s: %t\n",
        first, second, strings.HasPrefix(first, second))
    i := strings.Index(first, second)
    fmt.Printf("2. %s contains %s: %t,\n", first, second, i >= 0)
    if i >= 0 {
        fmt.Printf("2.1. at location %d,\n", i)
        for start := i+1;; {
            if i = strings.Index(first[start:], second); i < 0 {
                break
            }
            fmt.Printf("2.2. at location %d,\n", start+i)
            start += i+1
        }
        fmt.Println("2.2. and that's all")
    }
    fmt.Printf("3. %s ends with %s: %t\n",
        first, second, strings.HasSuffix(first, second))
}

func main() {
    match("abracadabra", "abr")
}


assert "abcd".startsWith("ab")
assert ! "abcd".startsWith("zn")
assert "abcd".endsWith("cd")
assert ! "abcd".endsWith("zn")
assert "abab".contains("ba")
assert ! "abab".contains("bb")

assert "abab".indexOf("bb") == -1 // not found flag
assert "abab".indexOf("ab") == 0

def indicesOf = { string, substring ->
    if (!string) { return [] }
    def indices = [-1]
    while (true) {
        indices << string.indexOf(substring, indices.last()+1)
        if (indices.last() == -1) break
    }
    indices[1..<(indices.size()-1)]
}
assert indicesOf("abab", "ab") == [0, 2]
assert indicesOf("abab", "ba") == [1]
assert indicesOf("abab", "xy") == []


> import Data.List
> "abc" `isPrefixOf` "abcdefg"
True
> "efg" `isSuffixOf` "abcdefg"
True
> "bcd" `isInfixOf` "abcdefg"
True
> "abc" `isInfixOf` "abcdefg" -- Prefixes and suffixes are also infixes
True
> let infixes a b = findIndices (isPrefixOf a) $ tails b
> infixes "ab" "abcdefabqqab"
[0,6,10]


procedure main()

   write("Matching s2 :=",image(s2 := "ab")," within s1:= ",image(s1 := "abcdabab"))

   write("Test #1 beginning ",if match(s2,s1) then "matches " else "failed")
   writes("Test #2 all matches at positions [")
      every writes(" ",find(s2,s1)|"]\n")
   write("Test #3 ending ", if s1[0-:*s2] == s2 then "matches" else "fails")

end


startswith=: ] -: ({.~ #)
contains=: +./@:E.~
endswith=: ] -: ({.~ [email protected]#)


"abcd".startsWith("ab") //returns true
"abcd".endsWith("zn") //returns false
"abab".contains("bb") //returns false
"abab".contains("ab") //returns true
int loc = "abab".indexOf("bb") //returns -1
loc = "abab".indexOf("ab") //returns 0
loc = "abab".indexOf("ab",loc+1) //returns 2


var stringA = "tacoloco"
  , stringB = "co"
  , q1, q2, q2multi, m
  , q2matches = []

// stringA starts with stringB
q1 = stringA.substring(0, stringB.length) == stringB

// stringA contains stringB
q2  = stringA.indexOf(stringB)

// multiple matches
q2multi = new RegExp(stringB,'g')

while(m = q2multi.exec(stringA)){
	q2matches.push(m.index)
}

// stringA ends with stringB
q3 = stringA.substr(-stringB.length) == stringB

console.log("1: Does '"+stringA+"' start with '"+stringB+"'? " + ( q1 ? "Yes." : "No."))
console.log("2: Is '"+stringB+"' contained in '"+stringA+"'? " + (~q2 ? "Yes, at index "+q2+"." : "No."))
if (~q2 && q2matches.length > 1){
	console.log("   In fact, it happens "+q2matches.length+" times within '"+stringA+"', at index"+(q2matches.length > 1 ? "es" : "")+" "+q2matches.join(', ')+".")
}
console.log("3: Does '"+stringA+"' end with '"+stringB+"'? "   + ( q3 ? "Yes." : "No."))


# startswith/1 is boolean:
"abc" | startswith("ab")
#=> true


startswith("abcd","ab")            #returns true
findfirst("ab", "abcd")            #returns 1:2, indices range where string was found
endswith("abcd","zn")              #returns false
match(r"ab","abcd") != Nothing     #returns true where 1st arg is regex string
for r in eachmatch(r"ab","abab")
	println(r.offset)
end                                #returns 1, then 3 matching the two starting indices where the substring was found


// version 1.0.6

fun main(args: Array<String>) {
    val s1 = "abracadabra"
    val s2 = "abra"
    println("$s1 begins with $s2 : ${s1.startsWith(s2)}")
    println("$s1 ends with $s2   : ${s1.endsWith(s2)}")
    val b  = s2 in s1
    print("$s1 contains $s2    : $b")
    if (b) println(" at locations ${s1.indexOf(s2) + 1} and ${s1.lastIndexOf(s2) + 1}")
    else println()
}


#!/bin/ksh
exec 2> /tmp/String_matching.err

# String matching
#	# 1. Determine if the first string starts with second string.
#	# 2. Determine if the first string contains the second string at any location
#	# 3. Determine if the first string ends with the second string
#	# 4. Print the location of the match for part 2
#	# 5. Handle multiple occurrences of a string for part 2

#	# Variables:
#
typeset -a bounds=( [0]="no Match" [1]="Starts with" [255]="Ends with" )

typeset -a string=( "Hello" "hello world" "William Williams" "Yabba dabba do" )
typeset -a substr=( "Hell" "Do" "abba" "Will" "orld" )

#	# Functions:
#
#	# Function _bounds(str, substr) - return 1 for starts with 255 for endswith
#
function _bounds {
	typeset _str ; _str="$1"
	typeset _sub ; _sub="$2"

	typeset _FALSE _STARTS _ENDS ; integer _FALSE=0 _STARTS=1 _ENDS=255

	[[ "${_str}" == "${_sub}"* ]] && return ${_STARTS}
	[[ "${_str}" == *"${_sub}" ]] && return ${_ENDS}
	return ${_FALSE}
}

#	# Function _contains(str, substr) - return 0 no match arr[pos1 ... posn]
#
function _contains {
	typeset _str ; _str="$1"
	typeset _sub ; _sub="$2"
	typeset _arr ; nameref _arr="$3"

	typeset _FALSE _TRUE _i _match _buff ; integer _FALSE=0 _TRUE=1 _i _match

	[[ "${_str}" != *"${_sub}"* ]] && return ${_FALSE}

	for ((_i=0; _i<=${#_str}-${#_sub}; _i++)); do
		_buff=${_str:${_i}:$((${#_str}-_i))}
		[[ ${_buff} != ${_buff#${_sub}} ]] && _arr+=( $(( _i+1 )) )
	done
	return ${_TRUE}
}

 ######
# main #
 ######

integer i j rc
typeset -a posarr

for ((i=0; i<${#string[*]}; i++)); do
	for ((j=0; j<${#substr[*]}; j++)); do
		_bounds "${string[i]}" "${substr[j]}" ; rc=$?
		print "${string[i]} ${bounds[rc]} ${substr[j]}"

		_contains "${string[i]}" "${substr[j]}" posarr ; rc=$?
		((! rc)) && print "${string[i]} ${substr[j]} ${bounds[rc]}es" && continue

		print "${string[i]} + ${substr[j]} ${#posarr[*]} matches at ${posarr[*]}"
		unset posarr ; typeset -a posarr
	done
done


{def S.in
 {def S.in.r {lambda {:c :w :i :n}
  {if {= :i :n}
   then -1
   else {if {W.equal? :c {W.get :i :w}}
   then :i
   else {S.in.r :c :w {+ :i 1} :n}}}}}
 {lambda {:c :w}
  {S.in.r :c :w 0 {W.length :w}}}}
-> S.in

{def startswith
 {lambda {:w1 :w2}
  {= {S.in _ {S.replace :w2 by _ in :w1}} 0}}}
-> startswith

{def endswith
 {lambda {:w1 :w2}
  {= {S.in _ {S.replace :w2 by _ in :w1}}
     {- {W.length :w1} {W.length :w2}}}}}
-> endswith

{def isin
 {lambda {:w1 :w2}
  {S.in _ {S.replace :w2 by _ in :w1}}}}
-> isin

{startswith nabuchodonosor nabu}
-> true
{startswith nabuchodonosor abu}
-> false

{endswith nabuchodonosor sor}
-> true
{endswith nabuchodonosor oso}
-> false

{isin nabuchodonosor oso}
-> 10   // is in at 10
{isin nabuchodonosor xyz}
-> -1   // is not in


: 2array  2 compress ; : bi*  '_ set dip _ execute ;  : [email protected]  dup bi* ;
: comb  "" split ;  : concat  "" join ;  : dip  swap '_ set execute _ ;
: first  0 extract swap drop ; : flip  comb reverse concat ;

: contains
    swap 'comb [email protected] length do                    # create a matrix.
         1 - "dup 1 1 compress rotate" dip dup 0 == if break then
    loop drop length compress swap drop
    "length 1 -" [email protected] rot 0 0 "'2array dip" '2array bi* swap 2array slice reverse
    : concat.(*)  concat ;
    'concat "'concat. apply" bi* eq 1 1 compress index collapse
    length if expand drop else drop 0 then ;    # r: position.
: end-with    'flip [email protected] start-with ;
: start-with  'comb [email protected] length rot swap iota subscript 'concat [email protected] eq ;

"rosettacode" "rosetta" start-with .    # 1
"rosettacode" "taco" contains .         # 5
"rosettacode" "ocat" contains .         # 0
"rosettacode" "edoc" end-with .         # 0
"rosettacode" "code" contains .         # 7


local(
 a = 'a quick brown peanut jumped over a quick brown fox',
 b = 'a quick brown'
)

//Determining if the first string starts with second string
#a->beginswith(#b) // true

//Determining if the first string contains the second string at any location
#a >> #b           // true
#a->contains(#b)   // true

//Determining if the first string ends with the second string
#a->endswith(#b)   // false


'1---Determining if the first string starts with second string
st1$="first string"
st2$="first"
if left$(st1$,len(st2$))=st2$ then
    print "First string starts with second string."
end if

'2---Determining if the first string contains the second string at any location
'2.1---Print the location of the match for part 2
st1$="Mississippi"
st2$="i"
if instr(st1$,st2$) then
    print "First string contains second string."
    print "Second string is at location ";instr(st1$,st2$)
end if

'2.2---Handle multiple occurrences of a string for part 2.
pos=instr(st1$,st2$)
while pos
    count=count+1
    pos=instr(st1$,st2$,pos+len(st2$))
wend
print "Number of times second string appears in first string is ";count

'3---Determining if the first string ends with the second string
st1$="first string"
st2$="string"
if right$(st1$,len(st2$))=st2$ then
    print "First string ends with second string."
end if


a = "Hello world!"
b = "Hello"

-- Determining if the first string starts with second string
put a starts b
-- 1

-- Determining if the first string contains the second string at any location
put a contains b
-- 1

-- Determining if the first string ends with the second string
put a.char[a.length-b.length+1..a.length] = b
-- 0

b = "world!"
put a.char[a.length-b.length+1..a.length] = b
-- 1

-- Print the location of the match for part 2
put offset(b, a)
-- 7


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 ends.with? :sub :thing
  if empty? :sub [output "true]
  if empty? :thing [output "false]
  if not equal? last :sub last :thing [output "false]
  output ends.with? butlast :sub butlast :thing
end

show starts.with? "dog "doghouse    ; true
show ends.with? "house "doghouse    ; true
show substring? "gho "doghouse       ; true  (built-in)


s1 = "string"
s2 = "str"
s3 = "ing"
s4 = "xyz"

print( "s1 starts with s2: ", string.find( s1, s2 ) == 1 )
print( "s1 starts with s3: ", string.find( s1, s3 ) == 1, "\n" )

print( "s1 contains s3: ", string.find( s1, s3 ) ~= nil )
print( "s1 contains s3: ", string.find( s1, s4 ) ~= nil, "\n" )

print( "s1 ends with s2: ", select( 2, string.find( s1, s2 ) ) == string.len( s1 ) )
print( "s1 ends with s3: ", select( 2, string.find( s1, s3 ) ) == string.len( s1 ) )


Module StringMatch {
      A$="Hello World"
      Print A$ ~ "Hello*"
      Print A$ ~ "*llo*"
      p=Instr(A$, "llo")
      Print p=3
      \\ Handle multiple occurance for "o"
      p=Instr(A$, "o")
      While p > 0 {
            Print "position:";p;{ for "o"}
            p=Instr(A$, "o", p+1)
      }
      Print A$ ~ "*orld"
}
StringMatch


> with( StringTools ): # bind package exports at the top-level
> s := "dzrIemaWWIMidXYZwGiqkOOn":
> s[1..4]; # pick a prefix
                                 "dzrI"

> IsPrefix( s[ 1 .. 4 ], s ); # check it
                                  true

> s[ -4 .. -1 ]; # pick a suffix
                                 "kOOn"

> IsSuffix( s[ -4 .. -1 ], s ); # check it
                                  true

> p := Search( "XYZ", s ); # find a substring
                                p := 14

> s[ p .. p + 2 ]; # check
                                 "XYZ"

> SearchAll( [ "WWI", "XYZ" ], s ); # search for multiple patterns
                            [8, 1], [14, 2]

> to 3 do s := cat( s, s ) end: length( s ); # build a longer string by repeated doubling
                                  192

> p := SearchAll( "XYZ", s ); # find all occurrences
                p := 14, 38, 62, 86, 110, 134, 158, 182

> {seq}( s[ i .. i + 2 ], i = p ); # check them
                                {"XYZ"}


StartWith[x_, y_] := MemberQ[Flatten[StringPosition[x, y]], 1]
EndWith[x_, y_] :=  MemberQ[Flatten[StringPosition[x, y]], StringLength[x]]
StartWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"]
EndWith["XYZaaabXYZaaaaXYZXYZ", "XYZ"]
StringPosition["XYZaaabXYZaaaaXYZXYZ", "XYZ"]


   % 1. Determining if the first string starts with second string
	strcmp(str1,str2,length(str2))
   % 2. Determining if the first string contains the second string at any location
	~isempty(strfind(s1,s2))
   % 3. Determining if the first string ends with the second string
	( (length(str1)>=length(str2)) && strcmp(str1(end+[1-length(str2):0]),str2) )

   % 1. Print the location of the match for part 2
	disp(strfind(s1,s2))
   % 2. Handle multiple occurrences of a string for part 2.
	ix = strfind(s1,s2);   % ix is a vector containing the starting positions of s2 within s1


(indexof 0 ==) :starts-with?
(indexof -1 !=) :contains?
((/ $/) swap 1 insert "" join regex ("") !=) :ends-with?

"minimalistic" "min" starts-with? puts!
"minimalistic" "list" contains? puts!
"minimalistic" "list" ends-with? puts!


string.startsWith = function(s)
    return self.len >= s.len and s[:s.len] == s
end function

string.endsWith = function(s)
    return self.len >= s.len and s[-s.len:] == s
end function

string.findAll = function(s)
    result = []
    after = null
    while true
        foundPos = self.indexOf(s, after)
        if foundPos == null then return result
        result.push foundPos
        after = foundPos + s.len - 1
    end while
end function

first = "The brown dog jumped jumped and jumped"
second = "jumped"

firstQ = """" + first + """"  // (first string, in quotes)
secondQ = """" + second + """"
doesOrNot = [" does not ", " does "]

print firstQ + doesOrNot[first.startsWith(second)] + "start with " + secondQ
print

found = first.findAll(second)
if not found then
    print firstQ + " does not contain " + secondQ + " anywhere"
else
    for pos in found
        print firstQ + " is found at position " + pos + " in " + secondQ
    end for
end if
print

print firstQ + doesOrNot[first.endsWith(second)] + "end with " + secondQ


/* NetRexx */
options replace format comments java crossref savelog symbols

lipsum = ''
x_ = 0
x_ = x_ + 1; lipsum[0] = x_; lipsum[x_] = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
x_ = x_ + 1; lipsum[0] = x_; lipsum[x_] = lipsum[1].reverse

srch = ''
srch[1] = 'Lorem ipsum dolor sit amet'
srch[2] = 'consectetur adipisicing elit'
srch[3] = 'dolore magna aliqua.'

loop j_ = 1 to lipsum[0]
  x1 = lipsum[j_].pos(srch[1])
  x2 = lipsum[j_].pos(srch[2])
  x3 = lipsum[j_].lastpos(srch[3])

  report(x1 = 1, lipsum[j_], srch[1], 'Test string starts with search string:', 'Test string does not start with search string:')
  report(x2 > 0, lipsum[j_], srch[2], 'Search string located in test string at position:' x2,  'Search string not found within test string:')
  report(x3 \= srch[3].length, lipsum[j_], srch[3], 'Test string ends with search string:', 'Test string does not start with search string:')
  end j_

many = ''
x_ = 0
x_ = x_ + 1; many[0] = x_; many[x_] = 'How many times does "many times" occur in this string?'
x_ = x_ + 1; many[0] = x_; many[x_] = 'How often does "many times" occur in this string?'
x_ = x_ + 1; many[0] = x_; many[x_] = 'How often does it occur in this string?'
srch[4] = 'many times'

loop j_ = 1 to many[0]
  o_ = 0
  k_ = 0
  loop label dups until o_ = 0
    o_ = many[j_].pos(srch[4], o_ + 1)
    if o_ \= 0 then k_ = k_ + 1
    end dups
  report(k_ > 0, many[j_], srch[4], 'Number of times search string occurs:' k_, 'Search string not found')
  end j_

method report(state = boolean, ts, ss, testSuccess, testFailure) public static
  if state then say testSuccess
  else          say testFailure
  say '    Test string:' ts
  say '  Search string:' ss
  say

  return


(setq str "abcdefbcghi")

;; test if str starts with "ab"
(starts-with str "ab")

;; find "bc" inside str
(find "bc" str)

;; test if str ends with "ghi"
(ends-with str "ghi")

;; find all positions of pattern inside str
(define (find-all-pos pattern str)
  (let ((idx -1) (pos '()))
    (while (setq idx (find pattern str 0 (+ idx 1)))
      (push idx pos -1))))

(find-all-pos "bc" str)


import strutils

let s = "The quick brown fox"
if s.startsWith("The quick"):
  echo "Starts with “The quick”."
if s.endsWith("brown Fox"):
  echo "Ends with “brown fox”."
if s.contains(" brown "):
  echo "Contains “ brown ”."
if "quick" in s:
  echo "Contains “quick”."      # Alternate form for "contains".

let pos = find(s, " brown ")    # -1 if not found.
if pos >= 0:
  echo "“ brown ” is located at position: " & $pos


bundle Default {
  class Matching {
    function : Main(args : System.String[]) ~ Nil {
      "abcd"->StartsWith("ab")->PrintLine(); # returns true
      "abcd"->EndsWith("zn")->PrintLine(); # returns false
      ("abab"->Find("bb") <> -1)->PrintLine(); # returns false
      ("abab"->Find("ab") <> -1)->PrintLine(); # returns true
      loc := "abab"->Find("bb"); # returns -1
      loc := "abab"->Find("ab"); # returns 0
      loc := "abab"->Find("ab", loc + 1); # returns 2
    }
  }
}


[@"abcd" hasPrefix:@"ab"] //returns true
[@"abcd" hasSuffix:@"zn"] //returns false
int loc = [@"abab" rangeOfString:@"bb"].location //returns -1
loc = [@"abab" rangeOfString:@"ab"].location //returns 0
loc = [@"abab" rangeOfString:@"ab" options:0 range:NSMakeRange(loc+1, [@"abab" length]-(loc+1))].location //returns 2


let match1 s1 s2 =
  let len1 = String.length s1
  and len2 = String.length s2 in
  if len1 < len2 then false else
    let sub = String.sub s1 0 len2 in
    (sub = s2)


: stringMatching(s1, s2)
| i |
   s2 isAllAt(s1, 1) ifTrue: [ System.Out s1 << " begins with " << s2 << cr ]
   s2 isAllAt(s1, s1 size s2 size - 1 + ) ifTrue: [ System.Out s1 << " ends with " << s2 << cr ]

   s1 indexOfAll(s2) ->i
   i ifNotNull: [ System.Out s1 << " includes " << s2 << " at position : " << i << cr ]

   "\nAll positions : " println
   1 ->i
   while (s1 indexOfAllFrom(s2, i) dup ->i notNull) [
      System.Out s1 << " includes " << s2 << " at position : " << i << cr
      i s2 size + ->i
      ] ;


string s="sdfkjhgsdfkdfgkbopefioqwurti487sdfkrglkjfs9wrtgjglsdfkdkjcnmmb.,msfjflkjsdfk"

string f="sdfk"

string cr=chr(13)+chr(10),tab=chr(9)

string pr="FIND STRING LOCATIONS" cr cr

sys a=0, b=1, count=0, ls=len(s), lf=len(f)

do
  a=instr b,s,f
  if a=0 then exit do
  count++
  if a=1 then  pr+="Begins with keyword" cr
  pr+=count tab a cr
  if a=ls-lf+1 then pr+="Ends with keyword at " a cr
  b=a+1
end do

pr+=cr "Total matches: " count cr

print pr

'FIND STRING LOCATIONS
'
'Begins with keyword
'1	1
'2	8
'3	32
'4	51
'5	73
'Ends with keyword at 73
'
'Total matches: 5


startsWith(string, prefix)={
  string=Vec(string);
  prefix=Vec(prefix);
  if(#prefix > #string, return(0));
  for(i=1,#prefix,if(prefix[i]!=string[i], return(0)));
  1
};
contains(string, inner)={
  my(good);
  string=Vec(string);
  inner=Vec(inner);
  for(i=0,#string-#inner,
    good=1;
    for(j=1,#inner,
      if(inner[j]!=string[i+j], good=0; break)
    );
    if(good, return(i+1))
  );
  0
};
endsWith(string, suffix)={
  string=Vec(string);
  suffix=Vec(suffix);
  if(#suffix > #string, return(0));
  for(i=1,#suffix,if(prefix[i]!=string[i+#string-#suffix], return(0)));
  1
};


$str1 =~ /^\Q$str2\E/  # true if $str1 starts with $str2
$str1 =~ /\Q$str2\E/   # true if $str1 contains $str2
$str1 =~ /\Q$str2\E$/  # true if $str1 ends with $str2


constant word = "the",                                      -- (also try this with "th"/"he")
         sentence = "the last thing the man said was the"
--       sentence = "thelastthingthemansaidwasthe"          -- (practically the same results)

-- A common, but potentially inefficient idiom for checking for a substring at the start is:
if match(word,sentence)=1 then
    ?"yes(1)"
end if
-- A more efficient method is to test the appropriate slice
if length(sentence)>=length(word)
and sentence[1..length(word)]=word then
    ?"yes(2)"
end if
-- Which is almost identical to checking for a word at the end
if length(sentence)>=length(word)
and sentence[-length(word)..-1]=word then
    ?"yes(3)"
end if
-- Or sometimes you will see this, a tiny bit more efficient:
if length(sentence)>=length(word)
and match(word,sentence,length(sentence)-length(word)+1) then
    ?"yes(4)"
end if
-- Finding all occurences is a snap:
integer r = match(word,sentence)
while r!=0 do
    ?r
    r = match(word,sentence,r+1)
end while
-- or equivalently:
?match_all(word,sentence)


<?php
/**********************************************************************************
* This program gets needle and haystack from the caller (chm.html) (see below)
* and checks for occurrences of the needle in the haystack
* 02.05.2013 Walter Pachl
* Comments or Suggestions welcome
**********************************************************************************/
$haystack = $_POST['haystack']; if ($haystack=='') {$haystack='no haystack given';}
$needle   = $_POST['needle'];   if ($needle=='')   {$needle='no needle given';}

function rexxpos($h,$n) {
  $pos = strpos($h,$n);
  if ($pos === false) { $pos=-1; }
  else                { $pos=$pos+1; }
  return ($pos);
 }

$pos=rexxpos($haystack,$needle);
$tx1 = "";
if ($pos==-1){ $n=0; }  // not found
else         { $n=1; }  // found once (so far)
// Special cases
if ($pos==1){ $tx1="needle found to be the start of the haystack"; }
if ($pos==strlen($haystack)-strlen($needle)+1)
            { $tx1="needle found at end of haystack"; }

if ($n>0) { // look for other occurrences
  $pl=$pos; // list of positions
  $p=$pos;  //
  $x="*************************************";
  $h=$haystack;
  while ($p>0) {
    $h=substr($x,0,$p).substr($h,$p);
    $p=rexxpos($h,$needle);
    if ( $p>0 ) { $n=$n+1; $pl=$pl.", ".$p; }
  }
       if ($n==1) { $txt="needle found once in haystack, position: $pl."; }
  else if ($n==2) { $txt="needle found twice in haystack, position(s): $pl."; }
  else            { $txt="needle found $n times in haystack, position(s): $pl."; }
}
else              { $txt="needle not found in haystack."; }
?>

    <title>Character Matching</title>
    <meta name="author" content="Walter Pachl">
    <meta name="date" content="02.05.2013">

Haystack: '<?php echo "$haystack" ?>'

Needle:   '<?php echo "$needle" ?>'

<?php echo "$txt" ?>

<?php echo "$tx1" ?>


import util.

go =>
  S1 = "string second",
  S2 = "string",

  %  - Determining if the first string starts with second string
  println("Using find/4"),
  if find(S1,S2,1,_) then
    println("S1 starts with S2")
  else
    println("S1 does not start with S2")
  end,

  println("Using append/3"),
  if append(S2,_,S1) then
    println("S1 starts with S2")
  else
    println("S1 does not start with S2")
  end,

  % - Determining if the first string contains the second string at any location
  S3 = "this is a string",
  S4 = "is a",
  if find(S3,S4,Start4,End4) then
    printf("S3 contains S4 at pos %d..%d\n", Start4,End4)
  else
    println("S3 does not contain S4")
  end,

  % - Determining if the first string ends with the second string
  S5 = "this is a string",
  S6 = "string",
  if find(S5,S6,Start6,S5.length) then
    printf("S5 ends with S6, startpos: %d\n",Start6)
  else
    println("S5 does not end with S6")
  end,

  if append(_,S6,S5) then
    println("S5 ends with S6")
  else
    println("S5 does not end with S6")
  end,

  S7 = "this is a string or a string",
  S8 = "a string",
  All = findall([Start8,End8], find(S7,S8,Start8,End8)),
  println(positions=All),

  % searching for " "
  All2 = findall([Start9,End9], find(S7," ",Start9,End9)),
  println(positions=All2),
  nl.


: (pre? "ab" "abcd")
-> "abcd"
: (pre? "xy" "abcd")
-> NIL

: (sub? "bc" "abcd")
-> "abcd"
: (sub? "xy" "abcd")
-> NIL

: (tail (chop "cd") (chop "abcd"))
-> ("c" "d")
: (tail (chop "xy") (chop "abcd"))
-> NIL

(de positions (Pat Str)
   (setq Pat (chop Pat))
   (make
      (for ((I . L) (chop Str) L (cdr L))
         (and (head Pat L) (link I)) ) ) )

: (positions "bc" "abcdabcd")
-> (2 6)


/*  Let s be one string, t be the other that might exist within s. */
                                                     /* 8-1-2011 */
k = index(s, t);
if k = 0 then put skip edit (t, ' is nowhere in sight') (a);
else if k = 1 then
   put skip edit (t, '  starts at the beginning of  ', s) (a);
else if k+length(t)-1 = length(s) then
   put skip edit (t, '  is at the end of  ', s) (a);
else put skip edit (t, '  is within  ', s) (a);

if k > 0 then put skip edit (t, '  starts at position  ', k) (a);


"spicywiener".StartsWith("spicy")
"spicywiener".Contains("icy")
"spicywiener".EndsWith("wiener")
"spicywiener".IndexOf("icy")
[regex]::Matches("spicywiener", "i").count


:- system:set_prolog_flag(double_quotes,codes) .

:- [library(lists)] .

%!  starts_with(FIRSTz,SECONDz)
%
% True if `SECONDz` is the beginning of `FIRSTz` .

starts_with(FIRSTz,SECONDz)
:-
lists:append(SECONDz,_,FIRSTz)
.

%!  contains(FIRSTz,SECONDz)
%
% True once if `SECONDz` is contained within `FIRSTz` at one or more positions .

contains(FIRSTz,SECONDz)
:-
contains(FIRSTz,SECONDz,_) ,
!
.

%!  contains(FIRSTz,SECONDz,NTH1)
%
% True if `SECONDz` is contained within `FIRSTz` at position `NTH1` .

contains(FIRSTz,SECONDz,NTH1)
:-
lists:append([PREFIXz,SECONDz,_SUFFIXz_],FIRSTz) ,
prolog:length(PREFIXz,NTH0) ,
NTH1 is NTH0 + 1
.

%!  ends_with(FIRSTz,SECONDz)
%
% True if `SECONDz` is the ending of `FIRSTz` .

ends_with(FIRSTz,SECONDz)
:-
lists:append(_,SECONDz,FIRSTz)
.


Procedure StartsWith(String1$, String2$)
  Protected Result
  If FindString(String1$, String2$, 1) =1 ; E.g Found in possition 1
    Result =CountString(String1$, String2$)
  EndIf
  ProcedureReturn Result
EndProcedure

Procedure EndsWith(String1$, String2$)
  Protected Result, dl=Len(String1$)-Len(String2$)
  If dl>=0 And Right(String1$, Len(String2$))=String2$
    Result =CountString(String1$, String2$)
  EndIf
  ProcedureReturn Result
EndProcedure


"abcd".startswith("ab") #returns True
"abcd".endswith("zn") #returns False
"bb" in "abab" #returns False
"ab" in "abab" #returns True
loc = "abab".find("bb") #returns -1
loc = "abab".find("ab") #returns 0
loc = "abab".find("ab",loc+1) #returns 2


DefStr S
DefInt P
string2 = "dogs"
string1 = "dogs and cats are often enemies,because dogs are stronger than cats, but cats sometimes can be friend to dogs"
position = 0
pcount = 0
Print "Searching "; string2; " into "; string1
While (InStr(position, string1, string2) > 0)
    position = InStr(position + 1, string1, string2)
    pcount = pcount + 1
    If position = 1 Then Print string1; "- starts with -"; string2
    Print position
    If position = Len(string1) - Len(string2) + 1 Then
        Print string1; "- ends with -"; string2
        Exit While
    End If
Wend
Print string2; " is present "; pcount; " times into "; string1


  [ tuck size split drop = ]       is starts   ( [ [ --> b )

  [ tuck size negate split nip = ] is ends     ( [ [ --> b )

  [ 2dup = iff true
    else
      [ over [] = iff false done
        2dup starts iff true done
        dip behead nip again ]
    dip 2drop ]                    is contains ( [ [ --> b )

  [ iff
      [ say "true" ]
    else
      [ say "false" ] ]           is echobool  (   b -->   )

  $ "abcdefgh" $ "abc" starts   echobool cr
  $ "abcdefgh" $ "xyz" starts   echobool cr
  $ "abcdefgh" $ "fgh" ends     echobool cr
  $ "abcdefgh" $ "xyz" ends     echobool cr
  $ "abcdefgh" $ "cde" contains echobool cr
  $ "abcdefgh" $ "xyz" contains echobool cr


#lang racket
(require srfi/13)
(string-prefix? "ab" "abcd")
(string-suffix? "cd" "abcd")
(string-contains "abab" "bb")
(string-contains "abab" "ba")


$haystack.starts-with($needle)  # True if $haystack starts with $needle
$haystack.contains($needle)     # True if $haystack contains $needle
$haystack.ends-with($needle)    # True if $haystack ends with $needle


: startsWith? ( $1 $2 - f )
  withLength &swap dip 0 swap ^strings'getSubset compare ;

"abcdefghijkl" "abcde" startsWith?
"abcdefghijkl" "bcd" startsWith?

"abcdefghijkl" "bcd" ^strings'search
"abcdefghijkl" "zmq" ^strings'search

: endsWith? ( $1 $2 - f )
  swap withLength + over getLength - compare ;

"abcdefghijkl" "ijkl" endsWith?
"abcdefghijkl" "abc" endsWith?


/*REXX program  demonstrates  some  basic   character string   testing  (for matching). */
parse arg A B                                    /*obtain A and B from the command line.*/
say 'string  A  = '    A                         /*display string   A   to the terminal.*/
say 'string  B  = '    B                         /*   "       "     B    "  "      "    */
say copies('░', 70)                              /*display a line separator  (fence).   */
LB= length(B)                                    /*get the length of string  B  in bytes*/
if left(A, LB)==B  then say  'string  A  starts with string  B'
                   else say  "string  A  doesn't start with string  B"
say                                              /* [↓] another method using COMPARE BIF*/
p= pos(B, A)
if p==0  then say  "string  A  doesn't contain string  B"
         else say  'string  A  contains string  B  (starting in position'   p")"
say
if right(A, LB)==B  then say 'string  A  ends with string  B'
                    else say "string  A  doesn't end with string  B"
say
$=;   p= 0;                       do  until p==0;          p= pos(B, A, p+1)
                                  if p\==0  then $= $','   p
                                  end   /*until*/

$= space( strip($, 'L', ",") )                   /*elide extra blanks and leading comma.*/
#= words($)                                      /*obtain number of words in  $  string.*/

if #==0  then say "string  A  doesn't contain string  B"
         else say 'string  A  contains string  B '    #    " time"left('s', #>1),
              "(at position"left('s', #>1)  $")" /*stick a fork in it,  we're all done. */


aString = "Welcome to the Ring Programming Language"
bString = "Ring"
bStringIndex = substr(aString,bString)
if bStringIndex > 0 see "" + bStringIndex + " : " + bString ok


p 'abcd'.start_with?('ab')  #returns true
p 'abcd'.end_with?('ab')    #returns false
p 'abab'.include?('bb')     #returns false
p 'abab'.include?('ab')     #returns true
p 'abab'['bb']              #returns nil
p 'abab'['ab']              #returns "ab"
p 'abab'.index('bb')        #returns nil
p 'abab'.index('ab')        #returns 0
p 'abab'.index('ab', 1)     #returns 2
p 'abab'.rindex('ab')       #returns 2


s1$ = "abc def ghi klmnop"
s2$  = "abc"  ' begins with
s3$  = "ef"   ' is in the string
s4$  = "nop"  ' ends with

sn2$ = "abcx"  ' not begins with
sn3$ = "efx"   ' not in the string
sn4$ = "nopx"  ' not ends with

if left$(s1$,len(s2$)) <> s2$ then a$ = "Not "
print "String:";s1$;" does ";a$;"begin with:";s2$

if instr(s1$,s3$) = 0 then a$ = "Not "
print "String:";s1$;" does ";a$;"contain:";s3$

if mid$(s1$,len(s1$) + 1 - len(s4$),len(s4$)) <> s4$ then a$ = "Not "
print "String:";s1$;" does ";a$;"end with:";s4$

' ----------- not -----------------------------
print
if left$(s1$,len(sn2$)) <> sn2$ then a$ = "Not "
print "String:";s1$;" does ";a$;"begin with:";sn2$

if instr(s1$,sn3$) = 0 then a$ = "Not "
print "String:";s1$;" does ";a$;"contain:";sn3$

if mid$(s1$,len(s1$) + 1 - len(sn4$),len(sn4$)) <> sn4$ then a$ = "Not "
print "String:";s1$;" does ";a$;"end with:";sn4$


fn print_match(possible_match: Option<usize>) {
    match possible_match {
        Some(match_pos) => println!("Found match at pos {}", match_pos),
        None => println!("Did not find any matches")
    }
}

fn main() {
    let s1 = "abcd";
    let s2 = "abab";
    let s3 = "ab";

    // Determining if the first string starts with second string
    assert!(s1.starts_with(s3));
    // Determining if the first string contains the second string at any location
    assert!(s1.contains(s3));
    // Print the location of the match
    print_match(s1.find(s3)); // Found match at pos 0
    print_match(s1.find(s2)); // Did not find any matches
    // Determining if the first string ends with the second string
    assert!(s2.ends_with(s3));
}


"abcd".startsWith("ab") //returns true
"abcd".endsWith("zn") //returns false
"abab".contains("bb") //returns false
"abab".contains("ab") //returns true

var loc="abab".indexOf("bb") //returns -1
loc = "abab".indexOf("ab") //returns 0
loc = "abab".indexOf("ab", loc+1) //returns 2


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: position is 0;
  begin
    writeln(startsWith("abcd", "ab")); # write TRUE
    writeln(endsWith("abcd", "zn"));   # write FALSE
    writeln(pos("abab", "bb") <> 0);   # write FALSE
    writeln(pos("abab", "ab") <> 0);   # write TRUE
    writeln(pos("abab", "bb"));        # write 0
    position := pos("abab", "ab");
    writeln(position);                 # position is 1
    position := pos("abab", "ab", succ(position));
    writeln(position);                 # position is 3
  end func;


var first = "abc-abcdef-abcd";
var second = "abc";

say first.begins_with(second);      #=> true
say first.contains(second);         #=> true
say first.ends_with(second);        #=> false

# Get and print the location of the match
say first.index(second);            #=> 0

# Find multiple occurrences of a string
var pos = -1;
while (pos = first.index(second, pos+1) != -1) {
    say "Match at pos: #{pos}";
}


a startsWith: b
a includesSubCollection: b. "inherited from superclass"
a includesString: b. "the same, but more readable"
a endsWith: b
a indexOfSubCollection: b "inherited"
a indexOfSubCollection: b startingAt: pos "inherited"
a indexOfString: b
a indexOfStringStartingAt: b


      s1 = 'abcdabefgab'
      s2 = 'ab'
      s3 = 'xy'
      OUTPUT = ?(s1 ? POS(0) s2)  "1. " s2 " begins " s1
      OUTPUT = ?(s1 ? POS(0) s3)  "1. " s3 " begins " s1  ;# fails

      n = 0
again s1 POS(n) ARB s2 @a                        :F(p3)
      OUTPUT = "2. " s2 " found at position "
+        a - SIZE(s2) " in " s1
      n = a                                      :(again)

p3    OUTPUT = ?(s1 ? s2 RPOS(0)) "3. " s2 " ends " s1
END


String.isPrefix "ab" "abcd"; (* returns true *)
String.isSuffix "zn" "abcd"; (* returns false *)
String.isSubstring "bb" "abab"; (* returns false *)
String.isSubstring "ab" "abab"; (* returns true *)
#2 (Substring.base (#2 (Substring.position "bb" (Substring.full "abab")))); (* returns 4 *)
val loc = #2 (Substring.base (#2 (Substring.position "ab" (Substring.full "abab")))); (* returns 0 *)
val loc' = #2 (Substring.base (#2 (Substring.position "ab" (Substring.extract ("abab", loc+1, NONE))))); (* returns 2 *)


var str = "Hello, playground"
str.hasPrefix("Hell")           //True
str.hasPrefix("hell")           //False

str.containsString("llo")       //True
str.containsString("xxoo")      //False

str.hasSuffix("playground")     //True
str.hasSuffix("world")          //False


templates find&{s:}
  when <'$s;.*'> do '$; starts with $s;' !
  when <'.*$s;'> do '$; ends with $s;' !
  when <'.*$s;.*'> do '$; contains $s;' !
  otherwise '$s; cannot be found in $;' !
end find

'abcd' -> find&{s:'ab'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'cd'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'bc'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'e'} -> !OUT::write


set isPrefix    [string equal -length [string length $needle] $haystack $needle]
set isContained [expr {[string first $needle $haystack] >= 0}]
set isSuffix    [string equal $needle [string range $haystack end-[expr {[string length $needle]-1}] end]]


$$ MODE TUSCRIPT
ASK "string1", string1=""
ASK "string2", string2=""

IF (string1.sw.string2)   THEN
PRINT string1," starts with     ",string2
ELSE
PRINT string1," not starts with ",string2
ENDIF
SET beg=STRING (string1,string2,0,0,0,end)
IF (beg!=0) THEN
PRINT string1," contains        ",string2
PRINT "  starting in position ",beg
PRINT "  ending   in position ",end
ELSE
PRINT string1," not contains    ",string2
ENDIF

IF (string1.ew.string2) THEN
PRINT string1," ends with       ",string2
ELSE
PRINT string1," not ends with   ",string2
ENDIF


(tree-case *args*
  ((big small)
   (cond
     ((< (length big) (length small))
      (put-line `@big is shorter than @small`))
     ((str= big small)
      (put-line `@big and @small are equal`))
     ((starts-with small big)
      (put-line `@small is a prefix of @big`))
     ((ends-with small big)
      (put-line `@small is a suffix of @big`))
     (t (iflet ((pos (search-str big small)))
          (put-line `@small occurs in @big at position @pos`)
          (put-line `@small does not occur in @big`)))))
  (otherwise
    (put-line `usage: @(ldiff *full-args* *args*) <bigstring> <smallstring>`)))


void main() {
    var text = "一二三四五六七八九十";
    var starts = "一二";
    var ends = "九十";
    var contains = "五六";
    var not_contain = "百";

    stdout.printf(@"text: $text\n\n", );
    stdout.printf(@"starts with $starts: $(text.has_prefix(starts))\n");
    stdout.printf(@"ends with $ends: $(text.has_suffix(ends))\n");
    stdout.printf(@"starts with $starts: $(text.has_suffix(starts))\n");
    stdout.printf(@"contains $contains: $(contains in text)\n");
    stdout.printf(@"contains $not_contain: $(contains in text)\n");
}


Public Sub string_matching()
    word = "the"                                        '-- (also try this with "th"/"he")
    sentence = "the last thing the man said was the"
    '--       sentence = "thelastthingthemansaidwasthe" '-- (practically the same results)

    '-- A common, but potentially inefficient idiom for checking for a substring at the start is:
    If InStr(1, sentence, word) = 1 Then
        Debug.Print "yes(1)"
    End If
    '-- A more efficient method is to test the appropriate slice
    If Len(sentence) >= Len(word) _
        And Mid(sentence, 1, Len(word)) = word Then
        Debug.Print "yes(2)"
    End If
    '-- Which is almost identical to checking for a word at the end
    If Len(sentence) >= Len(word) _
        And Mid(sentence, Len(sentence) - Len(word) + 1, Len(word)) = word Then
        Debug.Print "yes(3)"
    End If
    '-- Or sometimes you will see this, a tiny bit more efficient:
    If Len(sentence) >= Len(word) _
    And InStr(Len(sentence) - Len(word) + 1, sentence, word) Then
        Debug.Print "yes(4)"
    End If
    '-- Finding all occurences is a snap:
    r = InStr(1, sentence, word)
    Do While r <> 0
        Debug.Print r
        r = InStr(r + 1, sentence, word)
    Loop
End Sub


Function StartsWith(s1,s2)
	StartsWith = False
	If Left(s1,Len(s2)) = s2 Then
		StartsWith = True
	End If
End Function

Function Contains(s1,s2)
	Contains = False
	If InStr(1,s1,s2) Then
		Contains = True & " at positions "
		j = 1
		Do Until InStr(j,s1,s2) = False
			Contains = Contains & InStr(j,s1,s2) & ", "
			If j = 1 Then
				If Len(s2) = 1 Then
					j = j + InStr(j,s1,s2)
				Else
					j = j + (InStr(j,s1,s2) + (Len(s2) - 1))
				End If
			Else
				If Len(s2) = 1 Then
					j = j + ((InStr(j,s1,s2) - j) + 1)
				Else
					j = j + ((InStr(j,s1,s2) - j) + (Len(s2) - 1))
				End If
			End If
		Loop
	End If
End Function

Function EndsWith(s1,s2)
	EndsWith = False
	If Right(s1,Len(s2)) = s2 Then
		EndsWith = True
	End If
End Function

WScript.StdOut.Write "Starts with test, 'foo' in 'foobar': " & StartsWith("foobar","foo")
WScript.StdOut.WriteLine
WScript.StdOut.Write "Contains test, 'o' in 'fooooobar': " & Contains("fooooobar","o")
WScript.StdOut.WriteLine
WScript.StdOut.Write "Ends with test, 'bar' in 'foobar': " & EndsWith("foobar","bar")


var s = "abracadabra"
var t = "abra"
var u = "ra"
var v = "cad"
System.print("'%(s)' starts with '%(t)' is %(s.startsWith(t))")
var indices = []
var start = 0
while (true) {
    var ix = s.indexOf(u, start)
    if (ix >= 0) {
        indices.add(ix)
        start = ix + u.count
        if (start >= s.count) break
    } else break
}
var contained = indices.count > 0
System.print("'%(s)' contains '%(u)' is %(contained) %(contained ? "at indices %(indices)" : "")")
System.print("'%(s)' ends with '%(v)' is %(s.endsWith(v))")


include c:\cxpl\codes;  \intrinsic 'code' declarations
string 0;               \use zero-terminated strings

func StrLen(A);         \Return number of characters in a string
char A;
int  I;
for I:= 0 to -1>>1-1 do
    if A(I) = 0 then return I;

func StrFind(A, B);     \Search for string B in string A
\Returns index of first occurrence of string B in A, or -1 if B is not found
char A, B;              \strings to be compared
int  LA, LB, I, J;
[LA:= StrLen(A);
 LB:= StrLen(B);
 for I:= 0 to LA-LB do
    [for J:= 0 to LB-1 do
        if B(J) # A(J+I) then J:= LB+1;
    if J = LB then return I;    \found
    ];
return -1;
];

char Str;  int I, J;
[Str:= "pack my box with";
\       0123456789012345
Text(0, if StrFind(Str, "pack") = 0 then "yes" else "no");  CrLf(0);    \1.
Text(0, if StrFind(Str,  "ack") = 0 then "yes" else "no");  CrLf(0);
I:= StrFind(Str, "x w");
Text(0, if I >= 0 then "yes" else "no");                                \2.
Text(0, ", at offset ");  IntOut(0, I);  CrLf(0);
I:= 0;  J:= 0;          \offsets of space characters
loop    [I:= StrFind(Str+J, " ");
        if I < 0 then quit;
        IntOut(0, I+J); ChOut(0, ^ );
        J:= J+I+1;
        ];
CrLf(0);
Text(0, if StrFind(Str, "X w") >= 0 then "yes" else "no");  CrLf(0);
Text(0, if StrFind(Str, "with") = StrLen(Str)-StrLen("with") then "yes" else "no");  CrLf(0); \3.
Text(0, if StrFind(Str, "x w" ) = StrLen(Str)-StrLen("x w" ) then "yes" else "no");  CrLf(0);
]


// XProfan can use StringParts, so the results here
// are the comma separated positions of the parts or 0
Proc Contains
   Parameters string content, part
   var string results = "0"
   var long posi = 1
   posi = InStr(part,content,posi)
   if posi <> 0
      results = str$(posi)
      repeat
         posi = InStr(part,content,posi+1)
         case posi <> 0 : results = results + "," + str$(posi)
      until posi == 0
   endif
   Return results
EndProc

Proc StartsWith
   Parameters string content, part
   Return if(Left$(content,Len(part)) == part, 1, 0)
EndProc

Proc EndsWith
   Parameters string content, part
   Return if(Right$(content,Len(part)) == part, 1, 0)
   'Return if(Left$(content,Len(content)-Len(part)+1) == part, 1, 0)
EndProc

var string theContent = "foobar"
var string thePart = "foo"
Print "Starts with: "
Print "  ("+thePart+" in "+theContent+") "+if(StartsWith(theContent,thePart),"Yes","No")
thePart = "back"
Print "  ("+thePart+" in "+theContent+") "+if(StartsWith(theContent,thePart),"Yes","No")

theContent = "foooooobar"
Print "Contains: "
Print "  ("+thePart+" in "+theContent+") "+ Contains(theContent,thePart)
thePart = "o"
Print "  ("+thePart+" in "+theContent+") "+ Contains(theContent,thePart)

theContent = "foobar"
thePart = "back"
Print "Ends with: "
Print "  ("+thePart+" in "+theContent+") "+if(EndsWith(theContent,thePart),"Yes","No")
thePart = "bar"
Print "  ("+thePart+" in "+theContent+") "+if(EndsWith(theContent,thePart),"Yes","No")

waitkey
end


cadena1$ = "qwertyuiop"

//Determinar si la primera cadena comienza con la segunda cadena
cadena2$ = "qwerty"
if left$(cadena1$, len(cadena2$)) = cadena2$ then
    print "'", cadena1$, "' comienza con '", cadena2$, "'"
else
    print "'", cadena1$, "' no comienza con '", cadena2$, "'"
end if

//Determinar si la primera cadena contiene la segunda cadena en cualquier
//ubicación imprima la ubicación de la coincidencia para la parte 2
cadena2$ = "wert"
posic = instr(cadena1$, cadena2$)
if posic then
    print "'", cadena1$, "' contiene '", cadena2$, "' en la posicion ", posic
else
    print "'", cadena1$, "' no contiene '", cadena2$, "'"
end if

//Determinar si la primera cadena termina con la segunda cadena
cadena2$ = "random garbage"
if right$(cadena1$, len(cadena2$)) = cadena2$ then
    print "'", cadena1$, "' termina con '", cadena2$, "'"
else
    print "'", cadena1$, "' no termina con '", cadena2$, "'"
end if
end


fcn f(text,p){ if(text.find(p)==0)println("Yep") else println("Nope") }
f("foobar","foo") //--> Yep
f("foobar","bar") //--> Nope


V s = ‘alphaBETA’
print(s.uppercase())
print(s.lowercase())


UCASE    CSECT
         USING  UCASE,R15
         MVC    UC,PG
         MVC    LC,PG
         OC     UC,=16C' '         or  X'40' uppercase
         NC     LC,=16X'BF'        and X'BF' lowercase
         XPRNT  PG,L'PG            print original
         XPRNT  UC,L'UC            print uc
         XPRNT  LC,L'LC            print lc
         BR     R14
PG       DC     CL9'alphaBETA'
UC       DS     CL(L'PG)
LC       DS     CL(L'PG)
         YREGS
         END    UCASE


	.lf  case6502.lst
	.cr  6502
	.tf  case6502.obj,ap1
;------------------------------------------------------
; String Case for the 6502 by barrym95838 2013.04.07
; Thanks to sbprojects.com for a very nice assembler!
; The target for this assembly is an Apple II with
;   mixed-case output capabilities.  Apple IIs like to
;   work in '+128' ascii, so this version leaves bit 7
;   alone, and can be used with either flavor.
; 6502s work best with data structures < 256 bytes;
;   several instructions would have to be added to
;   properly deal with longer strings.
; Tested and verified on AppleWin 1.20.0.0
;------------------------------------------------------
; Constant Section
;
StrPtr	 =   $6		;0-page temp pointer (2 bytes)
Low	 =   $8		;0-page temp low bound
High	 =   $9		;0-page temp high bound
CharOut	 =   $fded	;Specific to the Apple II
BigA	 =   "A"	;'A' for normal ascii
BigZ	 =   "Z"	;'Z'  "    "      "
LittleA	 =   "a"	;'a'  "    "      "
LittleZ	 =   "z"	;'z'  "    "      "
;======================================================
	.or  $0f00
;------------------------------------------------------
; The main program
;
main	ldx  #sTest	;Point to the test string
	lda  /sTest
	jsr  puts	;print it to stdout
	jsr  toUpper	;convert to UPPER-case
	jsr  puts	;print it
	jsr  toLower	;convert to lower-case
	jmp  puts	;print it and return to caller
;------------------------------------------------------
toUpper	ldy  #LittleA
	sty  Low	;set up the flip range
	ldy  #LittleZ
	bne  toLow2	;return via toLower's tail
;------------------------------------------------------
toLower	ldy  #BigA
	sty  Low	;set up the flip range
	ldy  #BigZ
toLow2	sty  High
	;		;return via fall-thru to flip
;------------------------------------------------------
; Given a NUL-terminated string at A:X, flip the case
;   of any chars in the range [Low..High], inclusive;
;   only works on the first 256 bytes of a long string
; Uses:  StrPtr, Low, High
; Preserves:  A, X
; Trashes:  Y
;
flip	stx  StrPtr	;init string pointer
	sta  StrPtr+1
	ldy  #0
	pha  		;save A
flip2	lda  (StrPtr),y	;get string char
	beq  flip5	;done if NUL
	cmp  Low
	bcc  flip4	;if Low <= char <= High
	cmp  High
	beq  flip3
	bcs  flip4
flip3	eor  #$20	;  then flip the case
	sta  (StrPtr),y
flip4	iny  		;point to next char
	bne  flip2	;loop up to 255 times
flip5	pla  		;restore A
	rts  		;return
;------------------------------------------------------
; Output NUL-terminated string @ A:X; strings longer
;   than 256 bytes are truncated there
; Uses:  StrPtr
; Preserves:  A, X
; Trashes:  Y
;
puts	stx  StrPtr	;init string pointer
	sta  StrPtr+1
	ldy  #0
	pha  		;save A
puts2	lda  (StrPtr),y	;get string char
	beq  puts3	;done if NUL
	jsr  CharOut	;output the char
	iny  		;point to next char
	bne  puts2	;loop up to 255 times
puts3	pla  		;restore A
	rts  		;return
;------------------------------------------------------
; Test String (in '+128' ascii, Apple II style)
;
sTest	.as	-"Alpha, BETA, gamma, {[(<[email protected]_>)]}."
	.az	-#13
;------------------------------------------------------
	.en


UpperCase:
;input: A0 = pointer to the string's base address.
;alters the string in-place.

MOVE.B (A0),D0      ;load a letter
BEQ .Terminated     ;we've reached the null terminator.

CMP.B #'a',D0       ;compare to ascii code for a
BCS .overhead       ;if less than a, keep looping.

CMP.B #'z',D0       ;compare to ascii code for z
BHI .overhead       ;if greater than z, keep looping

AND.B #%1101111,D0  ;this "magic constant" turns lower case to upper case, since they're always 32 apart.
.overhead:
MOVE.B D0,(A0)+     ;store the letter back and increment the pointer.
                    ;If this isn't an alphabetical character, D0 won't change and this store won't affect the string at all.
                    ;If it was a letter, it will have been changed to upper case before storing back.

BRA UpperCase       ;next letter

.Terminated:
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LowerCase:
MOVE.B (A0),D0      ;load a letter
BEQ .Terminated     ;we've reached the null terminator.

CMP.B #'A',D0       ;compare to ascii code for A
BCS .overhead       ;if less than A, keep looping.

CMP.B #'Z',D0       ;compare to ascii code for Z
BHI .overhead      ;if greater than Z, keep looping

OR.B #%00100000,D0  ;this "magic constant" turns upper case to lower case, since they're always 32 apart.
.overhead:
MOVE.B D0,(A0)+     ;store the result and get ready to read the next letter.
BRA LowerCase       ;next letter
.Terminated:
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ToggleCase:
MOVE.B (A0),D0     ;load a letter and inc the pointer to the next letter
BEQ .Terminated     ;we've reached the null terminator.

MOVE.B D0,D1        ;copy the letter
AND.B #%11011111    ;convert the copy to upper case so we can check it.

CMP.B #'A',D1       ;compare to ascii code for A
BCS overhead        ;if less than A, keep looping.

CMP.B #'Z',D1       ;compare to ascii code for Z
BHI overhead        ;if greater than Z, keep looping

EOR.B #%00100000,D0 ;swaps the case of the letter
overhead:
MOVE.B D0,(A0)+     ;store the result
BRA ToggleCase      ;next letter
.Terminated:
RTS


	org	100h
	jmp	demo
	;;;	Convert CP/M string under [HL] to upper case
unext:	inx	h
ucase:	mov	a,m	; Get character <- entry point is here
	cpi	'$'	; Done?
	rz		; If so, stop
	cpi	'a'	; >= 'a'?
	jc	unext	; If not, next character
	cpi	'z'+1	; <= 'z'?
	jnc	unext	; If not, next character
	sui	32	; Subtract 32
	mov	m,a	; Write character back
	jmp	unext
	;;;	Convert CP/M string under [HL] to lower case
lnext:	inx	h
lcase:	mov	a,m	; Get character <- entry point is here
	cpi	'$'	; Done?
	rz		; If so, stop
	cpi	'A'	; >= 'A'?
	jc	lnext	; If not, next character
	cpi	'Z'+1	; <= 'Z'?
	jnc	lnext	; If not, next character
	adi	32	; Subtract 32
	mov	m,a	; Write character back
	jmp	lnext
	;;;	Apply to given string
demo:	call	print	; Print without change
	lxi	h,str
	call	ucase	; Make uppercase
	call	print	; Print uppercase version
	lxi	h,str
	call	lcase	; Make lowercase (fall through to print)
print:	lxi	d,str	; Print string using CP/M call
	mvi	c,9
	jmp	5
str:	db	'alphaBETA',13,10,'$'


INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit

PROC UpperCase(CHAR ARRAY text,res)
  BYTE i

  res(0)=text(0)
  FOR i=1 TO res(0)
  DO
    res(i)=ToUpper(text(i))
  OD
RETURN

PROC LowerCase(CHAR ARRAY text,res)
  BYTE i

  res(0)=text(0)
  FOR i=1 TO res(0)
  DO
    res(i)=ToLower(text(i))
  OD
RETURN

PROC Main()
  CHAR ARRAY text="alphaBETA"
  CHAR ARRAY upper(20),lower(20)

  UpperCase(text,upper)
  LowerCase(text,lower)

  Put(125) PutE() ;clear screen
  PrintF("Original string: ""%S""%E",text)
  PrintF("Upper-case string: ""%S""%E",upper)
  PrintF("Lower-case string: ""%S""%E",lower)
RETURN


var string:String = 'alphaBETA';
var upper:String = string.toUpperCase();
var lower:String = string.toLowerCase();


with Ada.Characters.Handling, Ada.Text_IO;
use  Ada.Characters.Handling, Ada.Text_IO;

procedure Upper_Case_String is
   S : constant String := "alphaBETA";
begin
   Put_Line (To_Upper (S));
   Put_Line (To_Lower (S));
end Upper_Case_String;


#!/usr/local/bin/a68g --script #

# Demonstrate toupper and tolower for standard ALGOL 68
strings.  This does not work for multibyte character sets. #

INT l2u = ABS "A" - ABS "a";

PROC to upper = (CHAR c)CHAR:
  (ABS "a" > ABS c | c |: ABS c > ABS "z" | c | REPR ( ABS c + l2u ));

PROC to lower = (CHAR c)CHAR:
  (ABS "A" > ABS c | c |: ABS c > ABS "Z" | c | REPR ( ABS c - l2u ));

# Operators can be defined in ALGOL 68 #
OP (CHAR)CHAR TOLOWER = to lower, TOUPPER = to upper;

# upper-cases s in place #
PROC string to upper = (REF STRING s)VOID:
    FOR i FROM LWB s TO UPB s DO s[i] := to upper(s[i]) OD;

# lower-cases s in place #
PROC string to lower = (REF STRING s)VOID:
    FOR i FROM LWB s TO UPB s DO s[i] := to lower(s[i]) OD;

main: (
    STRING t := "alphaBETA";
    string to upper(t);
    printf(($"uppercase: "gl$, t));
    string to lower(t);
    printf(($"lowercase: "gl$, t))
)


begin
    % algol W doesn't have standard case conversion routines, this is one way %
    % such facilities could be provided                                       %

    % converts text to upper case                                             %
    % assumes the letters are contiguous in the character set (as in ASCII)   %
    % would not work in EBCDIC (as the original algol W implementations used) %
    procedure upCase( string(256) value result text ) ;
        for i := 0 until 255 do begin
            string(1) c;
            c := text( i // 1 );
            if c >= "a" and c <= "z"
            then begin
                text( i // 1 ) := code( decode( "A" )
                                      + ( decode( c ) - decode( "a" ) )
                                      )
            end
        end upCase ;

    % converts text to lower case                                             %
    % assumes the letters are contiguous in the character set (as in ASCII)   %
    % would not work in EBCDIC (as the original algol W implementations used) %
    procedure dnCase( string(256) value result text ) ;
        for i := 0 until 255 do begin
            string(1) c;
            c := text( i // 1 );
            if c >= "A" and c <= "Z"
            then begin
                text( i // 1 ) := code( decode( "a" )
                                      + ( decode( c ) - decode( "A" ) )
                                      )
            end
        end dnCase ;

    string(256) text;
    text := "alphaBETA";
    upCase( text );
    write( text( 0 // 40 ) );
    dnCase( text );
    write( text( 0 // 40 ) );

end.


#include <hopper.h>

#proto swapcase(_X_)

main:

   // literal:
   String to process = "alphaBETA", {"String to process: ",String to process}println
   {"UPPER: ",String to process} upper,println
   {"LOWER: ",String to process} lower,println
   {"SWAP CASE: "}
   s="", let( s := _swap case(String to process)),{s}println
   // arrays:
   vArray=0, {5,5} new array(vArray), vArray=String to process
   {"ARRAY UPPER: \n",vArray} upper,println
   {"ARRAY LOWER: \n",vArray} lower,println
   [1:2:end,1:2:end]get(vArray),upper, put(vArray)
   [2:2:end,2:2:end]get(vArray),lower, put(vArray)
   {"INTERVAL ARRAY UPPER/LOWER: \n",vArray},println

exit(0)

.locals
swapcase(_X_)
   nLen=0, {_X_}len,mov(nLen)
   __SWAPCASE__:
      if( [nLen:nLen]get(_X_),{"upper"}!typechar? )
          lower
      else
          upper
      end if
      put(_X_)
      --nLen,{nLen}jnz(__SWAPCASE__)
   {_X_}   // put processed string into the stack...
back


      a←'abcdefghijklmnopqrstuvwxyz'
      A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

      X←'alphaBETA'

      (a,⎕AV)[(A,⎕AV)⍳'alphaBETA']
alphabeta
      (A,⎕AV)[(a,⎕AV)⍳'alphaBETA']
ALPHABETA


use framework "Foundation"

-- TEST -----------------------------------------------------------------------
on run

    ap({toLower, toTitle, toUpper}, {"alphaBETA αβγδΕΖΗΘ"})

    --> {"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"}

end run

-- GENERIC FUNCTIONS ----------------------------------------------------------

-- toLower :: String -> String
on toLower(str)
    set ca to current application
    ((ca's NSString's stringWithString:(str))'s ¬
        lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower

-- toTitle :: String -> String
on toTitle(str)
    set ca to current application
    ((ca's NSString's stringWithString:(str))'s ¬
        capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toTitle

-- toUpper :: String -> String
on toUpper(str)
    set ca to current application
    ((ca's NSString's stringWithString:(str))'s ¬
        uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toUpper

-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
    set {nf, nx} to {length of fs, length of xs}
    set lst to {}
    repeat with i from 1 to nf
        tell mReturn(item i of fs)
            repeat with j from 1 to nx
                set end of lst to |λ|(contents of (item j of xs))
            end repeat
        end tell
    end repeat
    return lst
end ap

-- 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


main():
  uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io


str: "alphaBETA"

print ["uppercase  :" upper str]
print ["lowercase  :" lower str]
print ["capitalize :" capitalize str]


a := "alphaBETA"
StringLower, b, a ; alphabeta
StringUpper, c, a ; ALPHABETA

StringUpper, d, a, T ; Alphabeta (T = title case) eg "alpha beta gamma" would become "Alpha Beta Gamma"


$sString = "alphaBETA"
$sUppercase = StringUpper($sString) ;"ALPHABETA"
$sLowercase = StringLower($sString) ;"alphabeta"


Print: uppercase "alphaBETA";
Print: lowercase "alphaBETA";


BEGIN {
  a = "alphaBETA";
  print toupper(a), tolower(a)
}


s$ = "alphaBETA"
PRINT UCASE$(s$)
PRINT LCASE$(s$)


get "libhdr"

// Check whether a character is an upper or lowercase letter
let islower(x) = 'a' <= x <= 'z'
let isupper(x) = 'A' <= x <= 'Z'

// Convert a character to upper or lowercase
let toupper(x) = islower(x) -> x - 32, x
let tolower(x) = isupper(x) -> x + 32, x

// Map a character function over a string
let strmap(f,s) = valof
$(  for i=1 to s%0 do s%i := f(s%i)
    resultis s
$)

// Convert a string to upper or lowercase
let strtoupper(s) = strmap(toupper,s)
let strtolower(s) = strmap(tolower,s)

let start() be
$(  let s = "alphaBETA"
    writef("   String: %S*N", s)
    writef("Uppercase: %S*N", strtoupper(s))
    writef("Lowercase: %S*N", strtolower(s))
$)


  "alphaBETA":?s
& out$str$(upp$!s \n low$!s)


blsq ) "alphaBETA"^^zz\/ZZ
"ALPHABETA"
"alphabeta"


/* Demonstrate toupper and tolower for
   standard C strings.
   This does not work for multibyte character sets. */
#include <ctype.h>
#include <stdio.h>

/* upper-cases s in place */
void str_toupper(char *s)
{
    while(*s)
    {
        *s=toupper(*s);
        s++;
    }
}

/* lower-cases s in place */
void str_tolower(char *s)
{
    while(*s)
    {
        *s=tolower(*s);
        s++;
    }
}

int main(int argc, char *argv[])
{
    char t[255]="alphaBETA";
    str_toupper(t);
    printf("uppercase: %s\n", t);
    str_tolower(t);
    printf("lowercase: %s\n", t);
    return 0;
}


class Program
{
    static void Main(string[] args)
    {
        string input;
        Console.Write("Enter a series of letters: ");
        input = Console.ReadLine();
        stringCase(input);
    }

    private static void stringCase(string str)
    {
        char[] chars = str.ToCharArray();
        string newStr = "";

        foreach (char i in chars)
            if (char.IsLower(i))
                newStr += char.ToUpper(i);
            else
                newStr += char.ToLower(i);
        Console.WriteLine("Converted: {0}", newStr);
    }
}


#include <algorithm>
#include <string>
#include <cctype>

/// \brief in-place convert string to upper case
/// \return ref to transformed string
void str_toupper(std::string &str) {
  std::transform(str.begin(),
                 str.end(),
                 str.begin(),
                 (int(*)(int)) std::toupper);
}

/// \brief in-place convert string to lower case
/// \return ref to transformed string
void str_tolower(std::string &str) {
  std::transform(str.begin(),
                 str.end(),
                 str.begin(),
                 (int(*)(int)) std::tolower);
}


(def string "alphaBETA")
(println (.toUpperCase string))
(println (.toLowerCase string))


string(TOUPPER alphaBETA s)
message(STATUS "Uppercase: ${s}")
string(TOLOWER alphaBETA s)
message(STATUS "Lowercase: ${s}")


       IDENTIFICATION DIVISION.
       PROGRAM-ID. string-case-85.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  example PIC X(9) VALUE "alphaBETA".

       01  result  PIC X(9).

       PROCEDURE DIVISION.
           DISPLAY "Example: " example

           *> Using the intrinsic functions.
           DISPLAY "Lower-case: " FUNCTION LOWER-CASE(example)

           DISPLAY "Upper-case: " FUNCTION UPPER-CASE(example)

           *> Using INSPECT
           MOVE example TO result
           INSPECT result CONVERTING "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
               TO "abcdefghijklmnopqrstuvwxyz"
           DISPLAY "Lower-case: " result

           MOVE example TO result
           INSPECT result CONVERTING "abcdefghijklmnopqrstuvwxyz"
               TO  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
           DISPLAY "Upper-case: " result

           GOBACK
           .


<cfset upper = UCase("alphaBETA")>
<cfset lower = LCase("alphaBETA")>


CL-USER> (string-upcase "alphaBETA")
"ALPHABETA"


MODULE AlphaBeta;
IMPORT StdLog,Strings;

PROCEDURE Do*;
VAR
	str,res: ARRAY 128 OF CHAR;
BEGIN
	str := "alphaBETA";
	Strings.ToUpper(str,res);
	StdLog.String("Uppercase:> ");StdLog.String(res);StdLog.Ln;
	Strings.ToLower(str,res);
	StdLog.String("Lowercase:> ");StdLog.String(res);StdLog.Ln
END Do;

END AlphaBeta.


void main() {
    import std.stdio, std.string;

    immutable s = "alphaBETA";
    s.toUpper.writeln;
    s.toLower.writeln;
}


OPEN (1,O,'TT:')              ;open video

STR="alphaBETA"

LOCASE STR
DISPLAY (1,STR,10)            ;alphabeta

UPCASE STR
DISPLAY (1,STR,10)            ;ALPHABETA


let str = "alphaBETA"

print("Lower case: ", str.Lower(), separator: "")
print("Upper case: ", str.Upper(), separator: "")
print("Capitalize: ", str.Capitalize(), separator: "")


(string-downcase "alphaBETA")
    → "alphabeta"
(string-upcase "alphaBETA")
    → "ALPHABETA"
(string-titlecase "alphaBETA")
    → "Alphabeta"
(string-randcase "alphaBETA")
    → "alphaBEtA"
(string-randcase "alphaBETA")
    → "AlPHaBeTA"


IMPORT STD; //Imports the Standard Library

STRING MyBaseString := 'alphaBETA';

UpperCased := STD.str.toUpperCase(MyBaseString);
LowerCased := STD.str.ToLowerCase(MyBaseString);
TitleCased := STD.str.ToTitleCase(MyBaseString);

OUTPUT (UpperCased);
OUTPUT (LowerCased);
OUTPUT (TitleCased);


import system'culture;

public program()
{
    string s1 := "alphaBETA";

    // Alternative 1
    console.writeLine(s1.lowerCase());
    console.writeLine(s1.upperCase());

    // Alternative 2
    console.writeLine(s1.toLower(currentLocale));
    console.writeLine(s1.toUpper(currentLocale));
    console.readChar()
}


String.downcase("alphaBETA")
# => alphabeta
String.upcase("alphaBETA")
# => ALPHABETA
String.capitalize("alphaBETA")
# => Alphabeta


import String exposing (toLower, toUpper)

s = "alphaBETA"

lower = toLower s
upper = toUpper s


let s = "alphaBETA"
let upper = s.ToUpper()
let lower = s.ToLower()


"alphaBETA" >lower  ! "alphabeta"
"alphaBETA" >upper  ! "ALPHABETA"
"alphaBETA" >title  ! "Alphabeta"
"ß" >case-fold      ! "ss"


fansh> a := "alphaBETA"
alphaBETA
fansh> a.upper // convert whole string to upper case
ALPHABETA
fansh> a.lower // convert whole string to lower case
alphabeta
fansh> a.capitalize  // make sure first letter is capital
AlphaBETA
fansh> "BETAalpha".decapitalize  // make sure first letter is not capital
bETAalpha


: tolower ( C -- c ) 32 or ;
: toupper ( c -- C ) 32 invert and ;
: lower ( addr len -- ) over + swap  do i [email protected] tolower i c!  loop ;
: upper ( addr len -- ) over + swap  do i [email protected] toupper i c!  loop ;


 program example

   implicit none

   character(9) :: teststring = "alphaBETA"

   call To_upper(teststring)
   write(*,*) teststring
   call To_lower(teststring)
   write(*,*) teststring

 contains

   subroutine To_upper(str)
     character(*), intent(in out) :: str
     integer :: i

     do i = 1, len(str)
       select case(str(i:i))
         case("a":"z")
           str(i:i) = achar(iachar(str(i:i))-32)
       end select
     end do
   end subroutine To_upper

   subroutine To_lower(str)
     character(*), intent(in out) :: str
     integer :: i

     do i = 1, len(str)
       select case(str(i:i))
         case("A":"Z")
           str(i:i) = achar(iachar(str(i:i))+32)
       end select
     end do
   end subroutine To_Lower

 end program example


' FB 1.05.0 Win64

Dim s As String = "alphaBETA"
Print UCase(s)
Print LCase(s)
Sleep


a = "alphaBETA"
println[lc[a]]
println[uc[a]]


window 1

CFStringRef s = @"alphaBETA"

print s
print ucase(s)
print lcase(s)

HandleEvents


Public Sub Main()
Dim sString As String = "alphaBETA "

Print UCase(sString)
Print LCase(sString)

End


#define cases
{
    x = 'alphaBETA';
    y = string_upper(x); // returns ALPHABETA
    z = string_lower(x); // returns alphabeta
    show_message(y);
    show_message(z);
}


package main

import (
    "fmt"
    "strings"
    "unicode"
    "unicode/utf8"
)

func main() {
    show("alphaBETA")
    show("alpha BETA")
    // Three digraphs that should render similar to DZ, Lj, and nj.
    show("Ǆǈǌ")
    // Unicode apostrophe in third word.
    show("o'hare O'HARE o’hare don't")
}

func show(s string) {
    fmt.Println("\nstring:         ",
        s, " len:", utf8.RuneCountInString(s), "runes") // DZLjnj
    fmt.Println("All upper case: ", strings.ToUpper(s)) // DZLJNJ
    fmt.Println("All lower case: ", strings.ToLower(s)) // dzljnj
    fmt.Println("All title case: ", strings.ToTitle(s)) // DzLjNj
    fmt.Println("Title words:    ", strings.Title(s))   // Dzljnj
    fmt.Println("Swapping case:  ",                     // DzLjNJ
        strings.Map(unicode.SimpleFold, s))
}


def str = 'alphaBETA'

println str.toUpperCase()
println str.toLowerCase()


import Data.Char

s = "alphaBETA"

lower = map toLower s
upper = map toUpper s


CHARACTER str = "alphaBETA"
EDIT(Text=str, UpperCase=LEN(str))
EDIT(Text=str, LowerCase=LEN(str))
EDIT(Text=str, UpperCase=1)


procedure main()
    write(map("alphaBETA"))
    write(map("alphaBETA",&lcase,&ucase))
end


str = "alphaBETA"
print, str
print, strupcase(str)
print, strlowcase(str)


   toupper 'alphaBETA'
ALPHABETA
   tolower 'alphaBETA'
alphabeta


String str = "alphaBETA";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
//Also works with non-English characters with no modification
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase()); //does not transalate "SS" to "ß"


alert( "alphaBETA".toUpperCase() );
alert( "alphaBETA".toLowerCase() );


# like ruby's downcase - only characters A to Z are affected
def ascii_downcase:
  explode | map( if 65 <= . and . <= 90 then . + 32  else . end) | implode;

# like ruby's upcase - only characters a to z are affected
def ascii_upcase:
  explode | map( if 97 <= . and . <= 122 then . - 32  else . end) | implode;


var msg = "alphaBETA";
;msg;
;msg.toUpperCase();
;msg.toLowerCase();

;msg.toTitle();
;msg.toLocaleUpperCase();
;msg.toLocaleLowerCase();


julia> uppercase("alphaBETA")
"ALPHABETA"

julia> lowercase("alphaBETA")
"alphabeta"


  s:"alphaBETA"
  upper:{i:_ic x; :[96<i; _ci i-32;_ci i]}'
  lower:{i:_ic x; :[91>i; _ci i+32;_ci i]}'
  upper s
"ALPHABETA"
  lower s
"alphabeta"


// version 1.0.6

fun main(args: Array<String>) {
    val s = "alphaBETA"
    println(s.toUpperCase())
    println(s.toLowerCase())
    println(s.capitalize())
    println(s.decapitalize())
}


{span {@ style="text-transform:lowercase"} alphaBETA } -> alphabeta
{span {@ style="text-transform:uppercase"} alphaBETA } -> ALPHABETA


// Direct string return
'alphaBETA'->uppercase&
'alphaBETA'->lowercase&

// Assignment and manipulation of variables
local(toupper = 'alphaBETA')
#toupper->uppercase
#toupper

local(tolower = 'alphaBETA')
#tolower->lowercase
#tolower


----------------------------------------
-- Lower to upper case (ASCII only)
-- @param {string} str
-- @return {string}
----------------------------------------
on toUpper (str)
  alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  len = str.length
  repeat with i = 1 to len
    pos = offset(str.char[i], alphabet)
    if pos > 0 then put alphabet.char[pos] into char i of str
  end repeat
  return str
end

----------------------------------------
-- Upper to lower case (ASCII only)
-- @param {string} str
-- @return {string}
----------------------------------------
on toLower (str)
  alphabet = "abcdefghijklmnopqrstuvwxyz"
  len = str.length
  repeat with i = 1 to len
    pos = offset(str.char[i], alphabet)
    if pos > 0 then put alphabet.char[pos] into char i of str
  end repeat
  return str
end


put upper("alphaBETA") && lower("alphaBETA")
ALPHABETA alphabeta


print uppercase "alphaBETA  ; ALPHABETA
print lowercase "alphaBETA  ; alphabeta


str = "alphaBETA"
print( string.upper(str) )
print( string.lower(str) )


define(`upcase', `translit(`$*', `a-z', `A-Z')')
define(`downcase', `translit(`$*', `A-Z', `a-z')')

define(`x',`alphaBETA')
upcase(x)
downcase(x)


str := "alphaBETA";
StringTools:-UpperCase(str);
StringTools:-LowerCase(str);


>> upper('alphaBETA')

ans =

ALPHABETA

>> lower('alphaBETA')

ans =

alphabeta


str = "alphaBETA"
print (toUpper str)
print (toLower str)


:- module string_case.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module list, string.

main(!IO) :-
   S = "alphaBETA",
   io.format("uppercase       : %s\n", [s(to_upper(S))], !IO),
   io.format("lowercase       : %s\n", [s(to_lower(S))], !IO),
   io.format("capitalize first: %s\n", [s(capitalize_first(S))], !IO).
   % We can use uncaptitalize_first/1 to ensure the first character in a
   % string is lower-case.


vardef isbetween(expr a, i, f) =
  if string a:
    if (ASCII(a) >= ASCII(i)) and (ASCII(a) <= ASCII(f)):
      true
    else:
      false
    fi
  else:
    false
  fi enddef;

vardef toupper(expr s) =
  save ?; string ?; ? := ""; d := ASCII"A" - ASCII"a";
  for i = 0 upto length(s)-1:
    if isbetween(substring(i, i+1) of s, "a", "z"):
      ? := ? & char(ASCII(substring(i,i+1) of s) + d)
    else:
      ? := ? & substring(i, i+1) of s
    fi;
  endfor
  ?
enddef;

vardef tolower(expr s) =
  save ?; string ?; ? := ""; d := ASCII"a" - ASCII"A";
  for i = 0 upto length(s)-1:
    if isbetween(substring(i, i+1) of s, "A", "Z"):
      ? := ? & char(ASCII(substring(i,i+1) of s) + d)
    else:
      ? := ? & substring(i, i+1) of s
    fi;
  endfor
  ?
enddef;


"alphaBETA" uppercase
"alphaBETA" lowercase
"alphaBETA" capitalize


mixedString = "alphaBETA"
print "Upper Case of " + mixedString + " is " + mixedString.upper
print "Lower Case of " + mixedString + " is " + mixedString.lower


echo -ag $upper(alphaBETA)
echo -ag $lower(alphaBETA)


MODULE TextCase EXPORTS Main;

IMPORT IO, Text, ASCII;

PROCEDURE Upper(txt: TEXT): TEXT =
  VAR
    len := Text.Length(txt);
    res := "";
  BEGIN
    FOR i := 0 TO len - 1 DO
      res := Text.Cat(res, Text.FromChar(ASCII.Upper[Text.GetChar(txt, i)]));
    END;
    RETURN res;
  END Upper;

PROCEDURE Lower(txt: TEXT): TEXT =
  VAR
    len := Text.Length(txt);
    res := "";
  BEGIN
    FOR i := 0 TO len - 1 DO
      res := Text.Cat(res, Text.FromChar(ASCII.Lower[Text.GetChar(txt, i)]));
    END;
    RETURN res;
  END Lower;

BEGIN
  IO.Put(Upper("alphaBETA\n"));
  IO.Put(Lower("alphaBETA\n"));
END TextCase.


STRCASE(S)
 SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 SET LO="abcdefghijklmnopqrstuvwxyz"
 WRITE !,"Given: "_S
 WRITE !,"Upper: "_$TRANSLATE(S,LO,UP)
 WRITE !,"Lower: "_$TRANSLATE(S,UP,LO)
 QUIT


string = "alphaBETA"

println upper(string)
println lower(string)


using System.Console;
using System.Globalization;

module StringCase
{
    Main() : void
    {
        def alpha = "alphaBETA";
        WriteLine(alpha.ToUpper());
        WriteLine(alpha.ToLower());

        WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));

    }
}


/* NetRexx */

options replace format comments java crossref savelog symbols

abc = 'alphaBETA'

say abc.upper
say abc.lower
say abc.upper(1, 1) -- capitalize 1st character


(upper-case "alphaBETA")
(lower-case "alphaBETA")


toupper 'alphaBETA'
=ALPHABETA
tolower 'alphaBETA'
=alphabeta


import strutils

var s: string = "alphaBETA_123"
echo s, " as upper case: ", toUpperAscii(s)
echo s, " as lower case: ", toLowerAscii(s)
echo s, " as capitalized: ", capitalizeAscii(s)
echo s, " as normal case: ", normalize(s)  # to lower case without underscores.


string := "alphaBETA";
string->ToUpper()->PrintLine();
string->ToLower()->PrintLine();


NSLog(@"%@", @"alphaBETA".uppercaseString);
NSLog(@"%@", @"alphaBETA".lowercaseString);

NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar"


let () =
  let str = "alphaBETA" in
  print_endline (String.uppercase_ascii str); (* ALPHABETA *)
  print_endline (String.lowercase_ascii str); (* alphabeta *)

  print_endline (String.capitalize_ascii str); (* AlphaBETA *)
;;


s = "alphaBETA";
slc = tolower(s);
suc = toupper(s);
disp(slc);
disp(suc);


declare
  Str = "alphaBETA"
in
  {System.showInfo {Map Str Char.toUpper}}
  {System.showInfo {Map Str Char.toLower}}


// Uppercase and Lowercase functions for a minimal standard Pascal
// where no library routines for these operations exist
PROGRAM upperlower;

// convert a character to uppercase
FUNCTION uch(ch: CHAR): CHAR;
	BEGIN
		uch := ch;
		IF ch IN ['a'..'z'] THEN
			uch := chr(ord(ch) AND $5F);
	END;

// convert a character to lowercase
FUNCTION lch(ch: CHAR): CHAR;
	BEGIN
		lch := ch;
		IF ch IN ['A'..'Z'] THEN
			lch := chr(ord(ch) OR $20);
	END;

// toggle uper/lower case character
FUNCTION ulch(ch: CHAR): CHAR;
	BEGIN
		ulch := ch;
		IF ch IN ['a'..'z'] THEN ulch := uch(ch);
		IF ch IN ['A'..'Z'] THEN ulch := lch(ch);
	END;

// convert a string to uppercase
FUNCTION ucase(str: STRING): STRING;
	var i: Integer;
	BEGIN
		ucase := '';
		FOR i := 1 TO Length(str) DO
			ucase := ucase + uch(str[i]);
	END;

// convert a string to lowercase
FUNCTION lcase(str: STRING): STRING;
	var i: Integer;
	BEGIN
		lcase := '';
		FOR i := 1 TO Length(str) DO
			lcase := lcase + lch(str[i]);
	END;

// reverse cases in a given string
FUNCTION ulcase(str: STRING): STRING;
	var i: Integer;
	BEGIN
		ulcase := '';
		FOR i := 1 TO Length(str) DO
			ulcase := ulcase + ulch(str[i]);
	END;

VAR
	ab : STRING = 'alphaBETA';

BEGIN
	// demonstration
	Writeln('Original string : ',ab);
	Writeln('Reversed case   : ',ulcase(ab));
	Writeln('Upper case      : ',ucase(ab));
	Writeln('Lower case      : ',lcase(ab));
END.


<@ ENU$$$LSTPSTLITLIT>UPP|
[<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@>
<@ SAY&&&LIT>alphaBETA</@>

</@>


my $string = "alphaBETA";
print uc($string), "\n"; # => "ALPHABETA"
print lc($string), "\n"; # => "alphabeta"
$string =~ tr/[a-z][A-Z]/[A-Z][a-z]/; print "$string\n"; # => ALPHAbeta

print ucfirst($string), "\n"; # => "AlphaBETA"
print lcfirst("FOObar"), "\n"; # => "fOObar"


constant s = "alphaBETA"
?upper(s)
?lower(s)


$str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta

echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz


main =>
   S = "alphaBETA",
   println(to_uppercase(S)),
   println(to_lowercase(S)).


(let Str "alphaBETA"
   (prinl (uppc Str))
   (prinl (lowc Str)) )


string s = "alphaBETA";
string s2 = "foo bar gazonk";

write("Upper: %O\nLower: %O\nCapitalize: %O\nSilly: %O\nElite: %O\n",
      upper_case(s),
      lower_case(s),
      String.capitalize(s),
      String.sillycaps(s2),
      String.Elite.elite_string(s2));


declare s character (20) varying initial ('alphaBETA');

put skip list (uppercase(s));
put skip list (lowercase(s));


DECLARE
    vc  VARCHAR2(40) := 'alphaBETA';
    ivc VARCHAR2(40);
    lvc VARCHAR2(40);
    uvc VARCHAR2(40);
BEGIN
    ivc := INITCAP(vc); -- 'Alphabeta'
    lvc := LOWER(vc);   -- 'alphabeta'
    uvc := UPPER(vc);   -- 'ALPHABETA'
END;


To run:
Start up.
Put "alphaBeta" into a string.
Uppercase the string.
Write the string to the console.
Lowercase the string.
Write the string to the console.
Capitalize the string.
Write the string to the console.
Wait for the escape key.
Shut down.


lvars str = 'alphaBETA';
lowertoupper(str) =>
uppertolower(str) =>


lowercase = (str) :
   low = ("")
   str length times (i) :
      low append(if (65 <= str(i) ord and str(i) ord <= 90) :
         "abcdefghijklmnopqrstuvwxyz"(str(i) ord - 65)
      . else :
         str(i)
      .)
   .
   low join("")
.
uppercase = (str) :
   upp = ("")
   str length times (i) :
      upp append(if (97 <= str(i) ord and str(i) ord <= 122) :
         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"(str(i) ord - 97)
      . else :
         str(i)
      .)
   .
   upp join("")
.

lowercase("alphaBETA") print
uppercase("alphaBETA") print


string ls_string
ls_string = 'alphaBETA'
ls_string  = Upper(ls_string)
ls_string  = Lower(ls_string)


$string = 'alphaBETA'
$lower  = $string.ToLower()
$upper  = $string.ToUpper()
$title  = (Get-Culture).TextInfo.ToTitleCase($string)

$lower, $upper, $title


s = "alphaBETA"
print s.upper() # => "ALPHABETA"
print s.lower() # => "alphabeta"

print s.swapcase() # => "ALPHAbeta"

print "fOo bAR".capitalize() # => "Foo bar"
print "fOo bAR".title() # => "Foo Bar"

import string
print string.capwords("fOo bAR") # => "Foo Bar"


DIM s AS STRING * 9
s = "alphaBETA"
PRINT "The original string: " + s
PRINT ""
PRINT "Translated to lowercase: " + LCASE$(s)
PRINT "Translated to uppercase: " + UCASE$(s)


  [ $ "" swap
    witheach [ upper join ] ] is upper$ ( $ --> $ )

  [ $ "" swap
    witheach [ lower join ] ] is lower$ ( $ --> $ )

   $ "PaTrIcK, I dOn'T tHiNk WuMbO iS a ReAl wOrD."
   dup lower$ echo$ cr
       upper$ echo$ cr


 str <- "alphaBETA"
 toupper(str)
 tolower(str)


#lang racket
(define example "alphaBETA")

(string-upcase example)
;"ALPHABETA"
(string-downcase example)
;"alphabeta"
(string-titlecase example)
;"Alphabeta"


my $word = "alpha BETA" ;
say uc $word;         # all uppercase (subroutine call)
say $word.uc;         # all uppercase (method call)
# from now on we use only method calls as examples
say $word.lc;         # all lowercase
say $word.tc;         # first letter titlecase
say $word.tclc;       # first letter titlecase, rest lowercase
say $word.wordcase;   # capitalize each word


print ["Original: " original: "alphaBETA"]
print ["Uppercase:" uppercase original]
print ["Lowercase:" lowercase original]


str: "alphaBETA"
>> uppercase str
== "ALPHABETA"
>> lowercase str
== "alphabeta"
>> uppercase/part str 5
== "ALPHAbeta"


'alphaBETA s:to-upper s:put
'alphaBETA s:to-lower s:put


abc  = "abcdefghijklmnopqrstuvwxyz"              /*define all  lowercase  Latin letters.*/
abcU = translate(abc)                            /*   "    "   uppercase    "      "    */

x = 'alphaBETA'                                  /*define a string to a REXX variable.  */
y = translate(x)                                 /*uppercase  X  and store it ───►  Y   */
z = translate(x, abc, abcU)                      /*translate uppercase──►lowercase chars*/


aString = "WELCOME TO THE ring programming language"
see lower(aString) + nl
see upper(aString) + nl


"alphaBETA".downcase # => "alphabeta"
"alphaBETA".upcase # => "ALPHABETA"

"alphaBETA".swapcase # => "ALPHAbeta"
"alphaBETA".capitalize # => "Alphabeta"


fn main() {
    println!("{}", "jalapeño".to_uppercase()); // JALAPEÑO
    println!("{}", "JALAPEÑO".to_lowercase()); // jalapeño
}


val s="alphaBETA"
println(s.toUpperCase)   //-> ALPHABETA
println(s.toLowerCase)   //-> alphabeta
println(s.capitalize)    //-> AlphaBETA
println(s.reverse)       //-> ATEBahpla


(define s "alphaBETA")
(list->string (map char-upcase (string->list s)))
(list->string (map char-downcase (string->list s)))


echo "alphaBETA" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'


set letters to "alphaBETA"
put lowercase of letters // alphabeta
put uppercase of letters // ALPHABETA
put capitalized of letters // Alphabeta

repeat with each character of letters by reference
	if it is an uppercase
		set it to lowercase of it
	else
		set it to uppercase of it
	end if
end repeat

put letters //ALPHAbeta


say "alphaBETA".lc;             #=> alphabeta
say "alphaBETA".uc;             #=> ALPHABETA
say "alphaBETA".tc;             #=> AlphaBETA
say "alpha BETA".wc;            #=> Alpha Beta
say "alpha BETA".tc;            #=> Alpha BETA
say "alpha BETA".tclc;          #=> Alpha beta


TEXT soup, lower;
soup :- "alphaBETA";
lower :- LOWCASE(COPY(soup)); ! COPY, else soup is changed;
OutText("upper: "); OutText(UPCASE("alphaBETA"));
OutText(", lower: "); OutText(lower);
OutText(", soup: "); OutText(soup); Outimage;


'alphaBETA' toLowercase.
'alphaBETA' toUppercase.


'ALPHAbeta' asUppercase  "->'ALPHABETA' "
'ALPHAbeta' asLowercase "-> 'alphabeta' "


        define('uc(str)') :(uc_end)
uc      uc = replace(str,&lcase,&ucase) :(return)
uc_end

        define('lc(str)') :(lc_end)
lc      lc = replace(str,&ucase,&lcase) :(return)
lc_end

        define('ucfirst(str)ch') :(ucfirst_end)
ucfirst str len(1) . ch = uc(ch)
        ucfirst = str :(return)
ucfirst_end

        define('swapc(str)') :(swapc_end)
swapc   str = replace(str,&ucase &lcase, &lcase &ucase)
        swapc = str :(return)
swapc_end

*       # Test and display
        str = 'alphaBETA'
        output = str
        output = lc(str)
        output = uc(str)
        output = ucfirst(str)
        output = swapc(str)
end


DECLARE @s VARCHAR(10)
SET @s = 'alphaBETA'
print UPPER(@s)
print LOWER(@s)


VALUES UPPER('alphaBETA');
VALUES LOWER('alphaBETA');
VALUES initcap('alphaBETA');
-- Within a SQL query.
SELECT UPPER('alphaBETA') FROM sysibm.sysdummy1;


val strupr = String.map Char.toUpper;
val strlwr = String.map Char.toLower;


. scalar s="alphaBETA"
. di strupper(s)
ALPHABETA
. di strlower(s)
alphabeta


import Foundation

println("alphaBETA".uppercaseString)
println("alphaBETA".lowercaseString)
println("foO BAr".capitalizedString)


set string alphaBETA

# three built-in case conversion commands
string toupper $string  ;# ==> ALPHABETA
string tolower $string  ;# ==> alphabeta
string totitle $string  ;# ==> Alphabeta

# not built-in
proc swapcase {s} {
    foreach char [split $s ""] {
        if {$char eq [set CHAR [string toupper $char]]} {
            append new [string tolower $char]
        } else {
            append new $CHAR
        }
    }
    return $new
}
swapcase $string  ;# ==> ALPHAbeta

# better performance, but English alphabet only
proc swapcase_en {s} {
    string map {
        a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z
        A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z
    } $s
}

swapcase Père     ;# ==> pÈRE
swapcase_en Père  ;# ==> pèRE


 needs ctype

 [ i 1 - ] is i
 [ string.getLength 0 [ dup i + [email protected] toupper over i + c! ] countedLoop ] is string.toUpper
 [ string.getLength 0 [ dup i + [email protected] tolower over i + c! ] countedLoop ] is string.toLower

 " alphaBETA" string.toUpper type cr
 " alphaBETA" string.toLower type cr


 $string = "alphaBETA";
 $upperCase = strUpr($string);
 $lowerCase = strLwr($string);


#lang transd

MainModule: {
    _start: (λ
        (with s "alphaBETA"
            (lout (toupper s))
            (lout (tolower s)))
    )
}


$$ MODE TUSCRIPT,{}
string="alphaBETA"
lowercase =EXCHANGE(string," {&a} {-0-} ")
uppercase1=EXCHANGE(string," {&a} {-0+} ")
uppercase2=CAPS    (string)
PRINT lowercase
PRINT uppercase1
PRINT uppercase2


echo alphaBETA | tr '[a-z]' '[A-Z]'     # => ALPHABETA
echo alphaBETA | tr '[A-Z]' '[a-z]'     # => alphabeta


out (lower "alphaBETA") endl console
out (upper "alphaBETA") endl console


#import std

to_upper = * -:~& ~=`A-~p letters
to_lower = * -:~& ~=`A-~rlp letters

#show+

examples = <to_upper 'alphaBETA',to_lower 'alphaBETA'>


string s = "alphaBeta";
// stores ALPHABETA to string
string s_upper = s.up();
// stores alphabeta to string
string s_lower = s.down();


Function StringCase()
Dim s As String
s = "alphaBETA"
Debug.Print UCase(s)
Debug.Print LCase(s)
Debug.Print WorksheetFunction.Proper(s)
End Function


Dim MyWord
MyWord = UCase("alphaBETA")   ' Returns "ALPHABETA"
MyWord = LCase("alphaBETA")   ' Returns "alphabeta"


#1 = CP
IT("alphaBETA")
Case_Upper_Block(#1, CP)
Case_Lower_Block(#1, CP)