String functions are used in computer programming languages to manipulate a string or query information about a string (some do both).
Most programming languages that have a string datatype will have some string functions although there may be other low-level ways within each language to handle strings directly. In object-oriented languages, string functions are often implemented as properties and methods of string objects. In functional and list-based languages a string is represented as a list (of character codes), therefore all list-manipulation procedures could be considered string functions. However such languages may implement a subset of explicit string-specific functions as well.
For function that manipulate strings, modern object-oriented languages, like C# and Java have immutable strings and return a copy (in newly allocated dynamic memory), while others, like C manipulate the original string unless the programmer copies data to a new string. See for example Concatenation below.
The most basic example of a string function is the length(string) function. This function returns the length of a string literal.
length(string)
length("hello world")
Other languages may have string functions with similar or exactly the same syntax or parameters or outcomes. For example, in many languages the length function is usually represented as len(string). The below list of common functions aims to help limit this confusion.
String functions common to many languages are listed below, including the different names used. The below list of common functions aims to help programmers find the equivalent function in a language. Note, string concatenation and regular expressions are handled in separate pages. Statements in guillemets (« … ») are optional.
charAt(string,integer)
string[i]
string{i}
string(i)
Mid(string,i,1)
MID$(string,i,1)
string.Chars(i)
string(i:i)
string.charAt(i)
string.[i]
string.chars().nth(i)
string[i,1]
String.sub (string, i)
string !! i
(string-ref string i)
(char string i)
(elt string i)
(get string i)
substr(string, i, 1)
string.substr(i, 1)
string.at(i)
lists:nth(i, string)
[string characterAtIndex:i]
NSString *
string.sub(string, i, i)
(string):sub(i, i)
string at: i
string index string i
StringTake[string, {i}]
string@i
string (i:1)
${string_param:i:1}
i⌷string
{ Example in Pascal } var MyStr: string = 'Hello, World'; MyChar: Char; begin MyChar := MyStr[2]; // 'e'
# Example in ALGOL 68 # "Hello, World"[2]; // 'e'
// Example in C #include <stdio.h> // for printf char MyStr[] = "Hello, World"; printf("%c", *(MyStr+1)); // 'e' printf("%c", *(MyStr+7)); // 'W' printf("%c", MyStr[11]); // 'd' printf("%s", MyStr); // 'Hello, World' printf("%s", "Hello(2), World(2)"); // 'Hello(2), World(2)'
// Example in C++ #include <iostream> // for "cout" #include <string.h> // for "string" data type using namespace std; char MyStr1[] = "Hello(1), World(1)"; string MyStr2 = "Hello(2), World(2)"; cout << "Hello(3), World(3)"; // 'Hello(3), World(3)' cout << MyStr2[6]; // '2' cout << MyStr1.substr (5, 3); // '(1)'
// Example in C# "Hello, World"[2]; // 'l'
# Example in Perl 5 substr("Hello, World", 1, 1); # 'e'
# Examples in Python "Hello, World"[2] # 'l' "Hello, World"[-3] # 'r'
# Example in Raku "Hello, World".substr(1, 1); # 'e'
' Example in Visual Basic Mid("Hello, World",2,1)
' Example in Visual Basic .NET "Hello, World".Chars(2) ' "l"c
" Example in Smalltalk " 'Hello, World' at: 2. "$e"
//Example in Rust "Hello, World".chars().nth(2); // Some('l')
compare(string1,string2)
IF string1<string2 THEN -1 ELSE ABS (string1>string2) FI
cmp(string1, string2)
(string1 > string2) - (string1 < string2)
strcmp(string1, string2)
std.string.cmp(string1, string2)
StrComp(string1, string2)
string1 cmp string2
string1 compare: string2
string1 <=> string2
string1.compare(string2)
compare(string1, string2)
CompareStr(string1, string2)
string1.compareTo(string2)
string1.CompareTo(string2)
(compare string1 string2)
(string= string1 string2)
(string-compare string1 string2 p< p= p>)
compare string1 string2
String.compare (string1, string2)
[string]::Compare(string1, string2)
[string1 compare:string2]
LLT(string1,string2)
LLE(string1,string2)
LGT(string1,string2)
LGE(string1,string2)
string1.localeCompare(string2)
bytes.Compare([]byte(string1), []byte(string2))
string compare string1 string2
compare(string1,string2,count)
string1.cmp(string2)
# Example in Perl 5 "hello" cmp "world"; # returns -1
# Example in Python cmp("hello", "world") # returns -1
# Examples in Raku "hello" cmp "world"; # returns Less "world" cmp "hello"; # returns More "hello" cmp "hello"; # returns Same
/** Example in Rexx */ compare("hello", "world") /* returns index of mismatch: 1 */
; Example in Scheme (use-modules (srfi srfi-13)) ; returns index of mismatch: 0 (string-compare "hello" "world" values values values)
string1 OP string2
OP
=, <>, <, >, <=
>=
=, /=, ≠, <, >, <=, ≤
≥
EQ, NE, LT, LE, GE
GT
(stringOP? string1 string2)
=, -ci=, <, -ci<, >, -ci>, <=, -ci<=, >=
-ci>=
-ci
(stringOP string1 string2)
=, -ci=, <>, -ci<>, <, -ci<, >, -ci>, <=, -ci<=, >=
=, -equal, /=, -not-equal, <, -lessp, >, -greaterp, <=, -not-greaterp, >=
-not-lessp
=, /=, <, >, <=,
=, \=, <, >, <=
=, ¬=, <, >, <=, >=, ¬<
¬>
=, /=, <, >, <=
==, /=, <, >, =<
==, /=, <, >, <=
eq, ne, lt, gt, le
ge
==, !=, <, >, <=
-eq, -ceq, -ne, -cne, -lt, -clt, -gt, -cgt, -le, -cle, -ge,
-cge
c
==, ~=, <, >, <=
=, ~=, <, >, <=
>=; Also: .EQ., .NE., .LT., .LE., .GT.
.GE.
=, <>, <, >, <=, >=
==, <>, <, >, <=
string1.METHOD(string2)
METHOD
eq
ne
gt
lt
le
% Example in Erlang "hello" > "world". % returns false
# Example in Raku "art" gt "painting"; # returns False "art" lt "painting"; # returns True
# Example in Windows PowerShell "hello" -gt "world" # returns false
;; Example in Common Lisp (string> "art" "painting") ; returns nil (string< "art" "painting") ; returns non nil
concatenate(string1,string2)
string1 & string2
strcat(string1, string2)
char *
string1 . string2
string1 + string2
string1 ~ string2
(string-append string1 string2)
(concatenate 'string string1 string2)
(str string1 string2)
string1 || string2
string1 // string2
string1 ++ string2
string1 ^ string2
[string1 stringByAppendingString:string2]
string1 .. string2
string1 , string2
string1 string2
string1string2
string1 <> string2
{ Example in Pascal } 'abc' + 'def'; // returns "abcdef"
// Example in C# "abc" + "def"; // returns "abcdef"
' Example in Visual Basic "abc" & "def" ' returns "abcdef" "abc" + "def" ' returns "abcdef" "abc" & Null ' returns "abc" "abc" + Null ' returns Null
// Example in D "abc" ~ "def"; // returns "abcdef"
;; Example in common lisp (concatenate 'string "abc " "def " "ghi") ; returns "abc def ghi"
# Example in Perl 5 "abc" . "def"; # returns "abcdef" "Perl " . 5; # returns "Perl 5"
# Example in Raku "abc" ~ "def"; # returns "abcdef" "Perl " ~ 6; # returns "Perl 6"
contains(string,substring)
string_in_string(string, loc int, substring)
ContainsStr(string, substring)
strstr(string, substring) != NULL
string.Contains(substring)
string.contains(substring)
string.indexOf(substring) >= 0
strpos(string, substring) !== false
str_contains(string, substring)
pos(string, substring) <> 0
substring in string
string.find(string, substring) ~= nil
string.include?(substring)
Data.List.isInfixOf substring string
string includesSubstring: substring
String.isSubstring substring string
(search substring string)
(not (null (string-index substring string)))
(substring? substring string)
! StringFreeQ[string, substring]
index(string, substring, startpos)>0
index(string, substring, occurrence)>0
strings.Contains(string, substring)
string.find(substring) != string::npos
[string containsString:substring]
string.rangeOfString(substring) != nil
∨/substring⍷string
¢ Example in ALGOL 68 ¢ string in string("e", loc int, "Hello mate"); ¢ returns true ¢ string in string("z", loc int, "word"); ¢ returns false ¢
// Example In C# "Hello mate".Contains("e"); // returns true "word".Contains("z"); // returns false
# Example in Python "e" in "Hello mate" # returns true "z" in "word" # returns false
# Example in Raku "Good morning!".contains('z') # returns False "¡Buenos días!".contains('í'); # returns True
" Example in Smalltalk " 'Hello mate' includesSubstring: 'e' " returns true " 'word' includesSubstring: 'z' " returns false "
Tests if two strings are equal. See also #Compare and #Compare. Note that doing equality checks via a generic Compare with integer result is not only confusing for the programmer but is often a significantly more expensive operation; this is especially true when using "C-strings".
string1 == string2
string1 === string2
string1 .EQ. string2
strcmp(string1, string2) == 0
(string=? string1 string2)
string1 = string2
test string1 = string2
[ string1 = string2 ]
string1 eq string2
string1.equals(string2)
string1.Equals(string2)
string1 -eq string2
[string]::Equals(string1, string2)
[string1 isEqualToString:string2]
[string1 isEqual:string2]
string1 ≡ string2
string1.eq(string2)
// Example in C# "hello" == "world" // returns false
' Example in Visual Basic "hello" = "world" ' returns false
# Examples in Perl 5 'hello' eq 'world' # returns 0 'hello' eq 'hello' # returns 1
# Examples in Raku 'hello' eq 'world' # returns False 'hello' eq 'hello' # returns True
# Example in Windows PowerShell "hello" -eq "world" # returns false
⍝ Example in APL 'hello' ≡ 'world' ⍝ returns 0
find(string,substring)
string in string(substring, pos, string[startpos:])
InStr(«startpos,»string,substring)
INSTR$(string,substring)
index(string,substring)
index(string,substring«,startpos»)
string.index(substring,«,startpos»)
instr(«startpos,»string,substring)
strpos(string,substring«,startpos»)
locate(string, substring)
strstr(string, substring)
std.string.indexOf(string, substring)
pos(string, substring«, startpos»)
strings.Index(string, substring)
pos(substring, string)
pos(substring, string«,startpos»)
string.find(substring«,startpos»)
string.find(substring«,startpos«,endpos»»)
string.index(substring«,startpos«,endpos»»)
string.index(substring«,startpos»)
string.indexOf(substring«,startpos»)
string.IndexOf(substring«,startpos«, charcount»»)
string:str(string, substring)
(string-contains string substring)
(string-index substring string)
nil
List.findIndex (List.isPrefixOf substring) (List.tails string)
Str.search_forward (Str.regexp_string substring) string 0
Substring.size (#1 (Substring.position substring (Substring.full string)))
[string rangeOfString:substring].location
string.find(string, substring)
(string):find(substring)
string indexOfSubCollection: substring startingAt: startpos ifAbsent: aBlock
string findString: substring startingAt: startpos
startpos = INDEX(string, substring «,back» «, kind»)
POSITION(substring IN string)
index(string, substring, startpos )
index(string, substring, occurrence )
string.indexOf(substring«,startpos«, charcount»»)
string first substring string startpos
(substring⍷string)⍳1
string.find(substring)
None
Examples
(search "e" "Hello mate") ; returns 1 (search "z" "word") ; returns NIL
"Hello mate".IndexOf("e"); // returns 1 "Hello mate".IndexOf("e", 4); // returns 9 "word".IndexOf("z"); // returns -1
"Hello, there!".index('e') # returns 1 "Hello, there!".index('z') # returns Nil
(use-modules (srfi srfi-13)) (string-contains "Hello mate" "e") ; returns 1 (string-contains "word" "z") ; returns #f
' Examples in InStr("Hello mate", "e") ' returns 2 InStr(5, "Hello mate", "e") ' returns 10 InStr("word", "z") ' returns 0
'Hello mate' indexOfSubCollection:'ate' "returns 8"
'Hello mate' indexOfSubCollection:'late' "returns 0"
I'Hello mate' indexOfSubCollection:'late' ifAbsent:[ 99 ] "returns 99"
'Hello mate' indexOfSubCollection:'late' ifAbsent:[ self error ] "raises an exception"
find_character(string,char)
char in string(char, pos, string[startpos:])
instr(string, any char«,startpos»)
strchr(string,char)
std.string.find(string, dchar)
string.find(char«,startpos»)
pos(string, char«, startpos»)
strings.IndexRune(string,char)
string.indexOf(char«,startpos»)
string.IndexOf(char«,startpos«, charcount»»)
(position char string)
(char-index char string)
List.elemIndex char string
Just index
String.index string char
position = SCAN (string, set «, back» «, kind»)
position = VERIFY (string, set «, back» «, kind»)[a]
string indexOf: char ifAbsent: aBlock
string indexOf: char
string includes: char
aBlock
BlockClosure
true
false
index(string, char, startpos )
string.index(?char)
strpos(string,char,startpos)
string.indexOf(char«,startpos«, charcount»»)
string⍳char
// Examples in C# "Hello mate".IndexOf('e'); // returns 1 "word".IndexOf('z') // returns -1
; Examples in Common Lisp (position #\e "Hello mate") ; returns 1 (position #\z "word") ; returns NIL
^a Given a set of characters, SCAN returns the position of the first character found,[19] while VERIFY returns the position of the first character that does not belong to the set.[20]
format(formatstring, items)
associate(file, string); putf(file, $formatstring$, items)
Format(item, formatstring)
sprintf(formatstring, items)
item.fmt(formatstring)
io_lib:format(formatstring, items)
sprintf(outputstring, formatstring, items)
std::format(formatstring, items)
std.string.format(formatstring, items)
Format(formatstring, items)
fmt.Sprintf(formatstring, items)
printf formatstring items
formatstring % (items)
formatstring.format(items)
fformatstring
Printf.sprintf formatstring
items
Text.Printf.printf formatstring items
formatstring printf: items
String.format(formatstring, items)
String.Format(formatstring, items)
(format formatstring items)
(format nil formatstring items)
formatstring -f items
[NSString stringWithFormat:formatstring, items]
String(format:formatstring, items)
string.format(formatstring, items)
(formatstring):format(items)
WRITE (outputstring, formatstring) items
put string(string) edit(items)(format)
format formatstring items
formatnumbers ⍕ items
formatstring ⎕FMT items
format!(formatstring, items)
// Example in C# String.Format("My {0} costs {1:C2}", "pen", 19.99); // returns "My pen costs $19.99"
// Example in Object Pascal (Delphi) Format('My %s costs $%2f', ['pen', 19.99]); // returns "My pen costs $19.99"
// Example in Java String.format("My %s costs $%2f", "pen", 19.99); // returns "My pen costs $19.99"
# Examples in Raku sprintf "My %s costs \$%.2f", "pen", 19.99; # returns "My pen costs $19.99" 1.fmt("%04d"); # returns "0001"
# Example in Python "My %s costs $%.2f" % ("pen", 19.99); # returns "My pen costs $19.99" "My {0} costs ${1:.2f}".format("pen", 19.99); # returns "My pen costs $19.99"
#Example in Python 3.6+ pen = "pen" f"My {pen} costs {19.99}" #returns "My pen costs 19.99"
; Example in Scheme (format "My ~a costs $~1,2F" "pen" 19.99) ; returns "My pen costs $19.99"
/* example in PL/I */ put string(some_string) edit('My ', 'pen', ' costs', 19.99)(a,a,a,p'$$$V.99') /* returns "My pen costs $19.99" */
Tests if two strings are not equal. See also #Equality.
string1 ne string2
string1 NE string2
string1 /= string2
string1 # string2
(string<> string1 string2)
(string/= string1 string2)
(not= string1 string2)
string1 != string2
string1 !== string2
string1 \= string2
string1 ¬= string2
test string1 != string2
[ string1 != string2 ]
string1 -ne string2
-not [string]::Equals(string1, string2)
string1 ~= string2
string1 ≢ string2
string1.ne(string2)
// Example in C# "hello" != "world" // returns true
' Example in Visual Basic "hello" <> "world" ' returns true
;; Example in Clojure (not= "hello" "world") ; ⇒ true
# Example in Perl 5 'hello' ne 'world' # returns 1
# Example in Raku 'hello' ne 'world' # returns True
# Example in Windows PowerShell "hello" -ne "world" # returns true
see #Find
see #rfind
join(separator, list_of_strings)
std.string.join(array_of_strings, separator)
string:join(list_of_strings, separator)
implode(separator, array_of_strings)
separator.join(sequence_of_strings)
array_of_strings.join(separator)
(string-join array_of_strings separator)
(format nil "~{~a~^separator~}" array_of_strings)
(clojure.string/join separator list_of_strings)
(apply str (interpose separator list_of_strings))
strings.Join(array_of_strings, separator)
join(array_of_strings, separator)
String.concat separator list_of_strings
String.concatWith separator list_of_strings
Data.List.intercalate separator list_of_strings
Join(array_of_strings, separator)
String.Join(separator, array_of_strings)
String.join(separator, array_of_strings)
&{$OFS=$separator; "$array_of_strings"}
array_of_strings -join separator
[array_of_strings componentsJoinedByString:separator]
table.concat(table_of_strings, separator)
{|String streamContents: [ :stream | collectionOfAnything asStringOn: stream delimiter: separator ]
collectionOfAnything joinUsing: separator
array_of_strings.join(separator«, final_separator»)
sequence_of_strings.joinWithSeparator(separator)
1↓∊separator,¨list_of_strings
// Example in C# String.Join("-", {"a", "b", "c"}) // "a-b-c"
" Example in Smalltalk " #('a' 'b' 'c') joinUsing: '-' " 'a-b-c' "
# Example in Perl 5 join( '-', ('a', 'b', 'c')); # 'a-b-c'
# Example in Raku <a b c>.join('-'); # 'a-b-c'
# Example in Python "-".join(["a", "b", "c"]) # 'a-b-c'
# Example in Ruby ["a", "b", "c"].join("-") # 'a-b-c'
; Example in Scheme (use-modules (srfi srfi-13)) (string-join '("a" "b" "c") "-") ; "a-b-c"
left(string,n)
string (string'First .. string'First + n - 1)
substr(string, 0, n)
LEFT$(string,n)
strncpy(string2, string, n)
string.substr(0,n)
[string substringToIndex:n]
(apply str (take n string))
string[0 .. n]
string:substr(string, start, length)
(subseq string 0 n)
string[:n]
left(string,n «,padchar»)
string[0, n]
string[0..n - 1]
string[1, n]
string[ .. n]
string.Substring(0,n)
leftstr(string, n)
copy (string,1,n)
string.substring(0,n)
(string-take string n)
take n string
String.extract (string, n, NONE)
String.sub string 0 n
string.[..n]
string.sub(string, 1, n)
(string):sub(1, n)
string first: n
string(:n)
StringTake[string, n]
string («FUNCTION» LENGTH(string) - n:n)
string.substring(0, n)
n↑string.
string[0..n]
string[..n]
string.get(0..n)
string.get(..n)
# Example in Raku "Hello, there!".substr(0, 6); # returns "Hello,"
/* Examples in Rexx */ left("abcde", 3) /* returns "abc" */ left("abcde", 8) /* returns "abcde " */ left("abcde", 8, "*") /* returns "abcde***" */
; Examples in Scheme (use-modules (srfi srfi-13)) (string-take "abcde", 3) ; returns "abc" (string-take "abcde", 8) ; error
' Examples in Visual Basic Left("sandroguidi", 3) ' returns "san" Left("sandroguidi", 100) ' returns "sandroguidi"
see #length
string'Length
UPB string
echo "${#string_param}"
len(string)
length(string), string:len(string)
Len(string)
string.Length
chars(string)
string.chars
codes(string)
string.codes
string.size OR string.length
strlen(string)
string.length()
string.length
(string-length string)
(length string)
(count string)
String.length string
size string
length string
string.characters.count
count(string)
countElements(string)
string.len(string)
(string):len()
#string
string size
LEN(string)
LEN_TRIM(string)
StringLength[string]
«FUNCTION» LENGTH(string)
«FUNCTION» BYTE-LENGTH(string)
string length string
≢ string
string.len()
string.chars().count()
// Examples in C# "hello".Length; // returns 5 "".Length; // returns 0
# Examples in Erlang string:len("hello"). % returns 5 string:len(""). % returns 0
# Examples in Perl 5 length("hello"); # returns 5 length(""); # returns 0
# Examples in Raku "🏳️🌈".chars; chars "🏳️🌈"; # both return 1 "🏳️🌈".codes; codes "🏳️🌈"; # both return 4 "".chars; chars ""; # both return 0 "".codes; codes ""; # both return 0
' Examples in Visual Basic Len("hello") ' returns 5 Len("") ' returns 0
//Examples in Objective-C [@"hello" Length] //returns 5 [@"" Length] //returns 0
-- Examples in Lua ("hello"):len() -- returns 5 #"" -- returns 0
lowercase(string)
LCase(string)
lcase(string)
lc(string)
string.lc
tolower(char)
std.string.toLower(string)
transform(string.begin(), string.end(), result.begin(), ::tolower)
strtolower(string)
lower(string)
${string_param,,}
echo "string" | tr 'A-Z' 'a-z'
string.lower()
downcase(string)
string.downcase
strings.ToLower(string)
(string-downcase string)
(lower-case string)
String.lowercase string
String.map Char.toLower string
map Char.toLower string
string.toLowerCase()
to_lower(string)
string.ToLower()
string.lowercaseString
string.lower(string)
(string):lower()
string asLowercase
LOWER(string)
ToLowerCase[string]
«FUNCTION» LOWER-CASE(string)
string.toLower
string tolower string
string.to_lowercase()
// Example in C# "Wiki means fast?".ToLower(); // "wiki means fast?"
; Example in Scheme (use-modules (srfi srfi-13)) (string-downcase "Wiki means fast?") ; "wiki means fast?"
/* Example in C */ #include <ctype.h> #include <stdio.h> int main(void) { char string[] = "Wiki means fast?"; int i; for (i = 0; i < sizeof(string) - 1; ++i) { /* transform characters in place, one by one */ string[i] = tolower(string[i]); } puts(string); /* "wiki means fast?" */ return 0; }
# Example in Raku "Wiki means fast?".lc; # "wiki means fast?"
see #substring
string.partition(separator)
lists:partition(pred, string)
split /(separator)/, string, 2
split separator, string, 2
string.split( separator, 2 )
# Examples in Python "Spam eggs spam spam and ham".partition('spam') # ('Spam eggs ', 'spam', ' spam and ham') "Spam eggs spam spam and ham".partition('X') # ('Spam eggs spam spam and ham', "", "")
# Examples in Perl 5 / Raku split /(spam)/, 'Spam eggs spam spam and ham' ,2; # ('Spam eggs ', 'spam', ' spam and ham'); split /(X)/, 'Spam eggs spam spam and ham' ,2; # ('Spam eggs spam spam and ham');
replace(string, find, replace)
changestr(find, string, replace)
std.string.replace(string, find, replace)
Replace(string, find, replace)
change(string, find, replace)
string.Replace(find, replace)
str_replace(find, replace, string)
re:replace(string, find, replace, «{return, list}»)
string.replace(find, replace)
string.replaceAll(find_regex, replace)[38]
string.gsub(find, replace)
string =~ s/find_regex/replace/g[38]
string.subst(find, replace, :g)
string.replace(find, replace, "g") [39]
string.replace(/find_regex/g, replace)[38]
echo "string" | sed 's/find_regex/replace/g'[38]
${string_param//find_pattern/replace}
string -replace find_regex, replace[38]
Str.global_replace (Str.regexp_string find) replace string
[string stringByReplacingOccurrencesOfString:find withString:replace]
string.stringByReplacingOccurrencesOfString(find, withString:replace)
string.gsub(string, find, replace)
(string):gsub(find, replace)
string copyReplaceAll: find with: replace
string map {find replace} string
StringReplace[string, find -> replace]
strings.Replace(string, find, replace, -1)
INSPECT string REPLACING ALL/LEADING/FIRST find BY replace
find_regex ⎕R replace_regex ⊢ string
// Examples in C# "effffff".Replace("f", "jump"); // returns "ejumpjumpjumpjumpjumpjump" "blah".Replace("z", "y"); // returns "blah"
// Examples in Java "effffff".replace("f", "jump"); // returns "ejumpjumpjumpjumpjumpjump" "effffff".replaceAll("f*", "jump"); // returns "ejump"
// Examples in Raku "effffff".subst("f", "jump", :g); # returns "ejumpjumpjumpjumpjumpjump" "blah".subst("z", "y", :g); # returns "blah"
' Examples in Visual Basic Replace("effffff", "f", "jump") ' returns "ejumpjumpjumpjumpjumpjump" Replace("blah", "z", "y") ' returns "blah"
# Examples in Windows PowerShell "effffff" -replace "f", "jump" # returns "ejumpjumpjumpjumpjumpjump" "effffff" -replace "f*", "jump" # returns "ejump"
reverse(string)
reverse string
flip string
string.flip
lists:reverse(string)
strrev(string)
string[::-1]
(string-reverse string)
(reverse string)
string.reverse
new StringBuilder(string).reverse().toString()
std::reverse(string.begin(), string.end());
std::string
StrReverse(string)
string.Reverse()
implode (rev (explode string))
string.split("").reverse().join("")
string.reverse(string)
(string):reverse()
string reverse
StringReverse[string]
«FUNCTION» REVERSE(string)
string.toCharArray.toList.reversed.join()
String(string.characters.reverse())
String(reverse(string))
string reverse string
⌽string
string.chars().rev().collect::<String>()
echo string | rev
" Example in Smalltalk " 'hello' reversed " returns 'olleh' "
# Example in Perl 5 reverse "hello" # returns "olleh"
# Example in Raku "hello".flip # returns "olleh"
# Example in Python "hello"[::-1] # returns "olleh"
; Example in Scheme (use-modules (srfi srfi-13)) (string-reverse "hello") ; returns "olleh"
rfind(string,substring)
InStrRev(«startpos,» string,substring)
instrrev(«startpos,» string,substring)
rindex(string,substring«,startpos»)
string.rindex(substring«,startpos»)
strrpos(string,substring«,startpos»)
string.rfind(substring«,startpos»)
std.string.rfind(string, substring)
string.rfind(substring«,startpos«, endpos»»)
string.rindex(substring«,startpos«, endpos»»)
rpos(string, substring«,startpos»)
strings.LastIndex(string, substring)
string.lastIndexOf(substring«,startpos»)
string.LastIndexOf(substring«,startpos«, charcount»»)
(search substring string :from-end t)
[string rangeOfString:substring options:NSBackwardsSearch].location
Str.search_backward (Str.regexp_string substring) string (Str.length string - 1)
string.match(string, '.*()'..substring)
string:match('.*()'..substring)
Ada.Strings.Unbounded.Index(Source => string, Pattern => substring, Going => Ada.Strings.Backward)
string.lastIndexOf(substring«,startpos«, charcount»»)
string lastIndexOfString:substring
string last substring string startpos
(⌽<\⌽substring⍷'string')⍳1
string.rfind(substring)
; Examples in Common Lisp (search "e" "Hello mate" :from-end t) ; returns 9 (search "z" "word" :from-end t) ; returns NIL
// Examples in C# "Hello mate".LastIndexOf("e"); // returns 9 "Hello mate".LastIndexOf("e", 4); // returns 1 "word".LastIndexOf("z"); // returns -1
# Examples in Perl 5 rindex("Hello mate", "e"); # returns 9 rindex("Hello mate", "e", 4); # returns 1 rindex("word", "z"); # returns -1
# Examples in Raku "Hello mate".rindex("e"); # returns 9 "Hello mate".rindex("e", 4); # returns 1 "word".rindex('z'); # returns Nil
' Examples in Visual Basic InStrRev("Hello mate", "e") ' returns 10 InStrRev(5, "Hello mate", "e") ' returns 2 InStrRev("word", "z") ' returns 0
right(string,n)
string (string'Last - n + 1 .. string'Last)
Right(string,n)
RIGHT$(string,n)
strcpy(string2, string+n)
string.Substring(string.Length()-n)
string[len(string)-n:]
string.substring(string.length()-n)
string.slice(-n)
right(string,n «,padchar»)
substr(string,-n)
substr(string,*-n)
string.substr(*-n)
string[-n:]
${string_param: -n}
string[n]
(string-take-right string n)
string[-n..-1]
string[$-n .. $]
String.sub string (String.length string - n) n
string.sub(string, -n)
(string):sub(-n)
string last: n
StringTake[string, -n]
string (1:n)
¯n↑string.
string[n..]
string.get(n..)
// Examples in Java; extract rightmost 4 characters String str = "CarDoor"; str.substring(str.length()-4); // returns 'Door'
# Examples in Raku "abcde".substr(*-3); # returns "cde" "abcde".substr(*-8); # 'out of range' error
/* Examples in Rexx */ right("abcde", 3) /* returns "cde" */ right("abcde", 8) /* returns " abcde" */ right("abcde", 8, "*") /* returns "***abcde" */
; Examples in Scheme (use-modules (srfi srfi-13)) (string-take-right "abcde", 3) ; returns "cde" (string-take-right "abcde", 8) ; error
' Examples in Visual Basic Right("sandroguidi", 3) ' returns "idi" Right("sandroguidi", 100) ' returns "sandroguidi"
string.rpartition(separator)
# Examples in Python "Spam eggs spam spam and ham".rpartition('spam') ### ('Spam eggs spam ', 'spam', ' and ham') "Spam eggs spam spam and ham".rpartition('X') ### ("", "", 'Spam eggs spam spam and ham')
split(/separator/, string«, limit»)
split(separator, string«, limit»)
string.split(separator, «limit»)
explode(separator, string«, limit»)
string.split(separator«, limit-1»)
string.split(separator«, limit»)
string:tokens(string, sepchars)
strings.Split(string, separator)
strings.SplitN(string, separator, limit)
(string-tokenize string« charset« start« end»»»)
Split(string, sepchars«, limit»)
string.Split(sepchars«, limit«, options»»)
string -split separator«, limit«, options»»
Str.split (Str.regexp_string separator) string
std.string.split(string, separator)
[string componentsSeparatedByString:separator]
string.componentsSeparatedByString(separator)
TStringList.Delimiter, TStringList.DelimitedText
StringSplit[string, separator«, limit»]
string.split«(sepchars«, limit«, options»»)»
split string separator
(separator≠string)⊂string
separator(≠⊆⊢)string
string.split(separator)
string.split(limit, separator)
// Example in C# "abc,defgh,ijk".Split(','); // {"abc", "defgh", "ijk"} "abc,defgh;ijk".Split(',', ';'); // {"abc", "defgh", "ijk"}
% Example in Erlang string:tokens("abc;defgh;ijk", ";"). % ["abc", "defgh", "ijk"]
// Examples in Java "abc,defgh,ijk".split(","); // {"abc", "defgh", "ijk"} "abc,defgh;ijk".split(",|;"); // {"abc", "defgh", "ijk"}
{ Example in Pascal } var lStrings: TStringList; lStr: string; begin lStrings := TStringList.Create; lStrings.Delimiter := ','; lStrings.DelimitedText := 'abc,defgh,ijk'; lStr := lStrings.Strings[0]; // 'abc' lStr := lStrings.Strings[1]; // 'defgh' lStr := lStrings.Strings[2]; // 'ijk' end;
# Examples in Perl 5 split(/spam/, 'Spam eggs spam spam and ham'); # ('Spam eggs ', ' ', ' and ham') split(/X/, 'Spam eggs spam spam and ham'); # ('Spam eggs spam spam and ham')
# Examples in Raku 'Spam eggs spam spam and ham'.split(/spam/); # (Spam eggs and ham) split(/X/, 'Spam eggs spam spam and ham'); # (Spam eggs spam spam and ham)
see #Format
see #trim
see #Compare (integer result)
substring(string, startpos, endpos)
substr(string, startpos, numChars)
string[startpos:endpos]
string (startpos .. endpos)
Mid(string, startpos, numChars)
mid(string, startpos, numChars)
string[startpos+(⍳numChars)-~⎕IO]
MID$(string, startpos, numChars)
string.substr(startpos, numChars)
substr(string, startpos «,numChars, padChar»)
string[startpos, numChars]
string[startpos .. endpos-1]
string[startpos ... endpos]
string[startpos .. endpos]
string[startpos len numChars]
string.slice(startpos«, endpos»)
string.substr(startpos«, numChars»)
string.Substring(startpos, numChars)
string.substring(startpos«, endpos»)
copy(string, startpos, numChars)
(substring string startpos endpos)
(subseq string startpos endpos)
String.sub string startpos numChars
substring (string, startpos, numChars)
string:sub_string(string, startpos, endpos)
string:substr(string, startpos, numChars)
strncpy(result, string + startpos, numChars);
string[startpos .. endpos+1]
take numChars $ drop startpos string
[string substringWithRange:NSMakeRange(startpos, numChars)]
string.[startpos..endpos]
string.sub(string, startpos, endpos)
(string):sub(startpos, endpos)
string copyFrom: startpos to: endpos
string(startpos:endpos)
SUBSTRING(string FROM startpos «FOR numChars»)
StringTake[string, {startpos, endpos}]
string (startpos:numChars)
${string_param:startpos:numChars}
string[startpos..endpos]
string.get(startpos..endpos)
// Examples in C# "abc".Substring(1, 1): // returns "b" "abc".Substring(1, 2); // returns "bc" "abc".Substring(1, 6); // error
;; Examples in Common Lisp (subseq "abc" 1 2) ; returns "b" (subseq "abc" 2) ; returns "c"
% Examples in Erlang string:substr("abc", 2, 1). % returns "b" string:substr("abc", 2). % returns "bc"
# Examples in Perl 5 substr("abc", 1, 1); # returns "b" substr("abc", 1); # returns "bc"
# Examples in Raku "abc".substr(1, 1); # returns "b" "abc".substr(1); # returns "bc"
# Examples in Python "abc"[1:2] # returns "b" "abc"[1:3] # returns "bc"
/* Examples in Rexx */ substr("abc", 2, 1) /* returns "b" */ substr("abc", 2) /* returns "bc" */ substr("abc", 2, 6) /* returns "bc " */ substr("abc", 2, 6, "*") /* returns "bc****" */
uppercase(string)
UCase(string)
ucase(string)
toupper(string)
uc(string)
string.uc
toupper(char)
for(size_t i = 0, len = strlen(string); i< len; i++) string[i] = toupper(string[i]);
for (char *c = string; *c != '\0'; c++) *c = toupper(*c);
std.string.toUpper(string)
transform(string.begin(), string.end(), result.begin(), toupper)[33]
upcase(char)
strtoupper(string)
upper(string)
${string_param^^}
echo "string" | tr 'a-z' 'A-Z'
translate(string)
UPPER variables
PARSE UPPER VAR SrcVar DstVar
string.upper()
upcase(string)
string.upcase
strings.ToUpper(string)
(string-upcase string)
String.uppercase string
String.map Char.toUpper string
map Char.toUpper string
string.toUpperCase()
string.uppercase()
to_upper(string)
string.ToUpper()
string.uppercaseString
string.upper(string)
(string):upper()
string asUppercase
UPPER(string)
ToUpperCase[string]
«FUNCTION» UPPER-CASE(string)
string.toUpper
string toupper string
string.to_uppercase()
// Example in C# "Wiki means fast?".ToUpper(); // "WIKI MEANS FAST?"
# Example in Perl 5 uc("Wiki means fast?"); # "WIKI MEANS FAST?"
# Example in Raku uc("Wiki means fast?"); # "WIKI MEANS FAST?" "Wiki means fast?".uc; # "WIKI MEANS FAST?"
/* Example in Rexx */ translate("Wiki means fast?") /* "WIKI MEANS FAST?" */ /* Example #2 */ A='This is an example.' UPPER A /* "THIS IS AN EXAMPLE." */ /* Example #3 */ A='upper using Translate Function.' Translate UPPER VAR A Z /* Z="UPPER USING TRANSLATE FUNCTION." */
; Example in Scheme (use-modules (srfi srfi-13)) (string-upcase "Wiki means fast?") ; "WIKI MEANS FAST?"
' Example in Visual Basic UCase("Wiki means fast?") ' "WIKI MEANS FAST?"
trim or strip is used to remove whitespace from the beginning, end, or both beginning and end, of a string.
trim
strip
String.Trim([chars])
string.strip();
(.trim string)
sequence [ predicate? ] trim
(string-trim '(#\Space #\Tab #\Newline) string)
(string-trim string)
string.trim()
Trim(String)
string.strip()
strings.Trim(string, chars)
LTRIM(RTRIM(String))
strip(string [,option, char])
string:strip(string [,option, char])
string.strip
string.lstrip
string.rstrip
string.trim
trim(string)
[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
string withBlanksTrimmed
string withoutSpaces
string withoutSeparators
strip(string)
string trim $string
TRIM(string)
TRIM(ADJUSTL(string))
LTrim(string)
RTrim(String)
String.trim string
Other languages
In languages without a built-in trim function, it is usually simple to create a custom function which accomplishes the same task.
APL can use regular expressions directly:
Trim←'^ +| +$'⎕R''
Alternatively, a functional approach combining Boolean masks that filter away leading and trailing spaces:
Trim←{⍵/⍨(∨\∧∘⌽∨\∘⌽)' '≠⍵}
Or reverse and remove leading spaces, twice:
Trim←{(∨\' '≠⍵)/⍵}∘⌽⍣2
In AWK, one can use regular expressions to trim:
ltrim(v) = gsub(/^[ \t]+/, "", v) rtrim(v) = gsub(/[ \t]+$/, "", v) trim(v) = ltrim(v); rtrim(v)
or:
function ltrim(s) { sub(/^[ \t]+/, "", s); return s } function rtrim(s) { sub(/[ \t]+$/, "", s); return s } function trim(s) { return rtrim(ltrim(s)); }
There is no standard trim function in C or C++. Most of the available string libraries[55] for C contain code which implements trimming, or functions that significantly ease an efficient implementation. The function has also often been called EatWhitespace in some non-standard C libraries.
In C, programmers often combine a ltrim and rtrim to implement trim:
#include <string.h> #include <ctype.h> void rtrim(char *str) { char *s; s = str + strlen(str); while (--s >= str) { if (!isspace(*s)) break; *s = 0; } } void ltrim(char *str) { size_t n; n = 0; while (str[n] != '\0' && isspace((unsigned char) str[n])) { n++; } memmove(str, str + n, strlen(str) - n + 1); } void trim(char *str) { rtrim(str); ltrim(str); }
The open source C++ library Boost has several trim variants, including a standard one:[56]
#include <boost/algorithm/string/trim.hpp> trimmed = boost::algorithm::trim_copy("string");
With boost's function named simply trim the input sequence is modified in-place, and returns no result.
Another open source C++ library Qt, has several trim variants, including a standard one:[57]
#include <QString> trimmed = s.trimmed();
The Linux kernel also includes a strip function, strstrip(), since 2.6.18-rc1, which trims the string "in place". Since 2.6.33-rc1, the kernel uses strim() instead of strstrip() to avoid false warnings.[58]
strstrip()
strim()
A trim algorithm in Haskell:
import Data.Char (isSpace) trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace
may be interpreted as follows: f drops the preceding whitespace, and reverses the string. f is then again applied to its own output. Note that the type signature (the second line) is optional.
The trim algorithm in J is a functional description:
trim =. #~ [: (+./\ *. +./\.) ' '&~:
That is: filter (#~) for non-space characters (' '&~:) between leading (+./\) and (*.) trailing (+./\.) spaces.
#~
' '&~:
+./\
*.
+./\.
There is a built-in trim function in JavaScript 1.8.1 (Firefox 3.5 and later), and the ECMAScript 5 standard. In earlier versions it can be added to the String object's prototype as follows:
String.prototype.trim = function() { return this.replace(/^\s+/g, "").replace(/\s+$/g, ""); };
Perl 5 has no built-in trim function. However, the functionality is commonly achieved using regular expressions.
Example:
$string =~ s/^\s+//; # remove leading whitespace $string =~ s/\s+$//; # remove trailing whitespace
$string =~ s/^\s+|\s+$//g ; # remove both leading and trailing whitespace
These examples modify the value of the original variable $string.
$string
Also available for Perl is StripLTSpace in String::Strip from CPAN.
String::Strip
There are, however, two functions that are commonly used to strip whitespace from the end of strings, chomp and chop:
chomp
chop
In Raku, the upcoming sister language of Perl, strings have a trim method.
$string = $string.trim; # remove leading and trailing whitespace $string .= trim; # same thing
The Tcl string command has three relevant subcommands: trim, trimright and trimleft. For each of those commands, an additional argument may be specified: a string that represents a set of characters to remove—the default is whitespace (space, tab, newline, carriage return).
string
trimright
trimleft
Example of trimming vowels:
set string onomatopoeia set trimmed [string trim $string aeiou] ;# result is nomatop set r_trimmed [string trimright $string aeiou] ;# result is onomatop set l_trimmed [string trimleft $string aeiou] ;# result is nomatopoeia
XSLT includes the function normalize-space(string) which strips leading and trailing whitespace, in addition to replacing any whitespace sequence (including line breaks) with a single space.
normalize-space(string)
<xsl:variable name='trimmed'> <xsl:value-of select='normalize-space(string)'/> </xsl:variable>
XSLT 2.0 includes regular expressions, providing another mechanism to perform string trimming.
Another XSLT technique for trimming is to utilize the XPath 2.0 substring() function.
substring()
str::chars
std::iter::Iterator::nth
operator<=>
std::strong_ordering
std::weak_ordering
less
equal
equivalent
greater
.TRUE.
.FALSE.
Ord::cmp
Ordering
Less
Equal
Greater
==
!=
PartialEq
<
>
<=
PartialOrd
string1
+
Add
str::contains
std::basic_string::contains
str::find
startpos
formatstring
std::format
format
slice::join
&str
Range
0..n
RangeFrom
n..
RangeTo
..n
SliceIndex
str
str::get
str::len
std::iter::Iterator::count
transform
std::
<algorithm>
tolower
toupper
<ctype.h>
std::tolower
std::toupper
std::transform
std::transform(string.begin(), string.end(), result.begin(), (int (*)(int))std::tolower);
result
str::to_lowercase
str::replace
std::iter::Iterator::rev
std::iter::DoubleEndedIterator
std::iter::Iterator::collect
String
str::rfind
str::split
str::rsplit
numChars
endpos
str::to_uppercase
str::trim