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.

e.g. length("hello world") would return 11.

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.

Common string functions (multi language reference)

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. String concatenation and regular expressions are handled in separate pages. Statements in guillemets (« … ») are optional.

CharAt

DefinitioncharAt(string,integer) returns character.
DescriptionReturns character at index in the string.
EquivalentSee substring of length 1 character.
FormatLanguagesBase index
string[i]ALGOL 68, APL, Julia, Pascal, Object Pascal (Delphi), Seed71
string[i]C, C++, C#, Cobra, D, FreeBASIC, Go, Python, PHP, Ruby, Windows PowerShell, JavaScript, APL0
string{i}PHP (deprecated in 5.3)0
string(i)Ada≥1
Mid(string,i,1)VB1
MID$(string,i,1)BASIC1
string.Chars(i)VB.NET0
string(i:i)Fortran1
string.charAt(i)Java, JavaScript0
string.[i]OCaml, F#0
string.chars().nth(i)Rust0
string[i,1]Pick Basic1
String.sub (string, i)Standard ML0
string !! iHaskell0
(string-ref string i)Scheme0
(char string i)Common Lisp0
(elt string i)ISLISP0
(get string i)Clojure0
substr(string, i, 1)Perl 50
substr(string, i, 1) string.substr(i, 1)Raku0
substr(string, i, 1)PL/I1
substr(string, i, 1)REXX1
string.at(i)C++ (STL) (w/ bounds checking)0
lists:nth(i, string)Erlang1
[string characterAtIndex:i]Objective-C (NSString * only)0
string.sub(string, i, i) (string):sub(i, i)Lua1
string at: iSmalltalk (w/ bounds checking)1
string index string iTcl0
StringTake[string, {i}]Mathematica, Wolfram Language1
string@iEiffel1
string (i:1)COBOL1
${string_param:i:1}Bash0
i⌷stringAPL0 or 1

Compare (integer result)

Definitioncompare(string1,string2) returns integer.
DescriptionCompares two strings to each other. If they are equivalent, a zero is returned. Otherwise, most of these routines will return a positive or negative result corresponding to whether string1 is lexicographically greater than, or less than, respectively, than string2. The exceptions are the Scheme and Rexx routines which return the index of the first mismatch, and Smalltalk which answer a comparison code telling how the receiver sorts relative to string parameter.
FormatLanguages
IF string1<string2 THEN -1 ELSE ABS (string1>string2) FIALGOL 68
cmp(string1, string2)Python 2
(string1 > string2) - (string1 < string2)Python
strcmp(string1, string2)C, PHP
std.string.cmp(string1, string2)D
StrComp(string1, string2)VB, Object Pascal (Delphi)
string1 cmp string2Perl, Raku
string1 compare: string2Smalltalk (Squeak, Pharo)
string1 <=> string2Ruby, C++ (STL, C++20)
string1.compare(string2)C++ (STL), Swift (Foundation)
compare(string1, string2)Rexx, Seed7
compare(string1, string2, pad)Rexx
CompareStr(string1, string2)Pascal, Object Pascal (Delphi)
string1.compareTo(string2)Cobra, Java
string1.CompareTo(string2)VB .NET, C#, F#
(compare string1 string2)Clojure
(string= string1 string2)Common Lisp
(string-compare string1 string2 p< p= p>)Scheme (SRFI 13)
(string= string1 string2)ISLISP
compare string1 string2OCaml
String.compare (string1, string2)Standard ML
compare string1 string2Haskell
[string]::Compare(string1, string2)Windows PowerShell
[string1 compare:string2]Objective-C (NSString * only)
LLT(string1,string2) LLE(string1,string2) LGT(string1,string2) LGE(string1,string2)Fortran
string1.localeCompare(string2)JavaScript
bytes.Compare([]byte(string1), []byte(string2))Go
string compare string1 string2Tcl
compare(string1,string2,count)PL/I
string1.cmp(string2)Rust

Compare (relational operator-based, Boolean result)

Definitionstring1 OP string2 OR (compare string1 string2) returns Boolean.
DescriptionLexicographically compares two strings using a relational operator or function. Boolean result returned.
FormatLanguages
string1 OP string2, where OP can be any of =, <>, <, >, <= and >=Pascal, Object Pascal (Delphi), OCaml, Seed7, Standard ML, BASIC, VB, VB .NET, F#
string1 OP string2, where OP can be any of =, /=, ≠, <, >, <=, ≤ and ≥; Also: EQ, NE, LT, LE, GE and GTALGOL 68
(stringOP? string1 string2), where OP can be any of =, -ci=, <, -ci<, >, -ci>, <=, -ci<=, >= and -ci>= (operators starting with '-ci' are case-insensitive)Scheme
(stringOP string1 string2), where OP can be any of =, -ci=, <>, -ci<>, <, -ci<, >, -ci>, <=, -ci<=, >= and -ci>= (operators starting with '-ci' are case-insensitive)Scheme (SRFI 13)
(stringOP string1 string2), where OP can be any of =, -equal, /=, -not-equal, <, -lessp, >, -greaterp, <=, -not-greaterp, >= and -not-lessp (the verbal operators are case-insensitive)Common Lisp
(stringOP string1 string2), where OP can be any of =, /=, <, >, <=, and >=ISLISP
string1 OP string2, where OP can be any of =, \=, <, >, <= and >=Rexx
string1 OP string2, where OP can be any of =, ¬=, <, >, <=, >=, ¬< and ¬>PL/I
string1 OP string2, where OP can be any of =, /=, <, >, <= and >=Ada
string1 OP string2, where OP can be any of ==, /=, <, >, =< and >=Erlang
string1 OP string2, where OP can be any of ==, /=, <, >, <= and >=Haskell
string1 OP string2, where OP can be any of eq, ne, lt, gt, le and gePerl, Raku
string1 OP string2, where OP can be any of ==, !=, <, >, <= and >=C++ (STL), C#, D, Go, JavaScript, Python, PHP, Ruby, Rust, Swift
string1 OP string2, where OP can be any of -eq, -ceq, -ne, -cne, -lt, -clt, -gt, -cgt, -le, -cle, -ge, and -cge (operators starting with 'c' are case-sensitive)Windows PowerShell
string1 OP string2, where OP can be any of ==, ~=, <, >, <= and >=Lua
string1 OP string2, where OP can be any of =, ~=, <, >, <= and >=Smalltalk
string1 OP string2, where OP can be any of ==, /=, <, >, <= and >=; Also: .EQ., .NE., .LT., .LE., .GT. and .GE.Fortran
string1 OP string2 where OP can be any of =, <>, <, >, <=, >= as well as worded equivalentsCOBOL
string1 OP string2 where OP can be any of ==, <>, <, >, <= and >=Cobra
string1 OP string2 is available in the syntax, but means comparison of the pointers pointing to the strings, not of the string contents. Use the Compare (integer result) function.C, Java
string1.METHOD(string2) where METHOD is any of eq, ne, gt, lt, ge, leRust

Concatenation

Definitionconcatenate(string1,string2) returns string.
DescriptionConcatenates (joins) two strings to each other, returning the combined string. Some languages like C have mutable strings, so really the second string is being appended to the first string and the mutated string is returned.
FormatLanguages
string1 adjacent_to string2Rexx (abutment, equivalent to string1 || string2)
string1 whitespace string2Rexx (equivalent to string1 || ' ' || string2)
string1 & string2Ada, FreeBASIC, Seed7, BASIC, VB, VB .NET, COBOL (between literals only)
strcat(string1, string2)C, C++ (char * only)
string1 . string2Perl, PHP
string1 + string2ALGOL 68, C++ (STL), C#, Cobra, FreeBASIC, Go, Pascal, Object Pascal (Delphi), Java, JavaScript, Windows PowerShell, Python, Ruby, Rust, F#, Swift, Turing, VB
string1 ~ string2D, Raku
(string-append string1 string2)Scheme, ISLISP
(concatenate 'string string1 string2)Common Lisp
(str string1 string2)Clojure
string1 || string2Rexx, SQL, PL/I
string1 // string2Fortran
string1 ++ string2Erlang, Haskell
string1 ^ string2OCaml, Standard ML, F#
[string1 stringByAppendingString:string2]Objective-C (NSString * only)
string1 .. string2Lua
string1 , string2Smalltalk, APL
string1 string2SNOBOL
string1string2Bash
string1 <> string2Mathematica
concat string1 string2Tcl

Contains

Definitioncontains(string,substring) returns boolean
DescriptionReturns whether string contains substring as a substring. This is equivalent to using Find and then detecting that it does not result in the failure condition listed in the third column of the Find section. However, some languages have a simpler way of expressing this test.
RelatedFind
FormatLanguages
string_in_string(string, loc int, substring)ALGOL 68
ContainsStr(string, substring)Object Pascal (Delphi)
strstr(string, substring) != NULLC, C++ (char * only)
string.Contains(substring)C#, VB .NET, Windows PowerShell, F#
string.contains(substring)Cobra, Java (1.5+), Raku, Rust, C++ (C++23)
string.indexOf(substring) >= 0JavaScript
strpos(string, substring) !== falsePHP
str_contains(string, substring)PHP (8+)
pos(string, substring) <> 0Seed7
substring in stringCobra, Python (2.3+)
string.find(string, substring) ~= nilLua
string.include?(substring)Ruby
Data.List.isInfixOf substring stringHaskell (GHC 6.6+)
string includesSubstring: substringSmalltalk (Squeak, Pharo, Smalltalk/X)
String.isSubstring substring stringStandard ML
(search substring string)Common Lisp
(not (null (string-index substring string)))ISLISP
(substring? substring string)Clojure
! StringFreeQ[string, substring]Mathematica
index(string, substring, startpos)>0Fortran, PL/I
index(string, substring, occurrence)>0Pick Basic
strings.Contains(string, substring)Go
string.find(substring) != string::nposC++
[string containsString:substring]Objective-C (NSString * only, iOS 8+/OS X 10.10+)
string.rangeOfString(substring) != nilSwift (Foundation)
∨/substring⍷stringAPL

Equality

Tests if two strings are equal. See also #Compare and #Compare. 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".

FormatLanguages
string1 == string2Python, C++ (STL), C#, Cobra, Go, JavaScript (similarity), PHP (similarity), Ruby, Rust, Erlang, Haskell, Lua, D, Mathematica, Swift
string1 === string2JavaScript, PHP
string1 == string2 string1 .EQ. string2Fortran
strcmp(string1, string2) == 0C
(string=? string1 string2)Scheme
(string= string1 string2)Common Lisp, ISLISP
string1 = string2ALGOL 68, Ada, Object Pascal (Delphi), OCaml, Pascal, Rexx, Seed7, Standard ML, BASIC, VB, VB .NET, F#, Smalltalk, PL/I, COBOL
test string1 = string2 [ string1 = string2 ]Bourne Shell
string1 eq string2Perl, Raku, Tcl
string1.equals(string2)Cobra, Java
string1.Equals(string2)C#
string1 -eq string2 [string]::Equals(string1, string2)Windows PowerShell
[string1 isEqualToString:string2] [string1 isEqual:string2]Objective-C (NSString * only)
string1 ≡ string2APL
string1.eq(string2)Rust

Find

Definitionfind(string,substring) returns integer
DescriptionReturns the position of the start of the first occurrence of substring in string. If the substring is not found most of these routines return an invalid index value – -1 where indexes are 0-based, 0 where they are 1-based – or some value to be interpreted as Boolean FALSE.
Relatedinstrrev
FormatLanguagesIf not found
string in string(substring, pos, string[startpos:])ALGOL 68returns BOOL: TRUE or FALSE, and position in REF INT pos.
InStr(«startpos,»string,substring)VB (positions start at 1)returns 0
INSTR$(string,substring)BASIC (positions start at 1)returns 0
index(string,substring)AWKreturns 0
index(string,substring«,startpos»)Perl 5returns −1
index(string,substring«,startpos») string.index(substring,«,startpos»)Rakureturns Nil
instr(«startpos,»string,substring)FreeBASICreturns 0
strpos(string,substring«,startpos»)PHPreturns FALSE
locate(string, substring)Ingresreturns string length + 1
strstr(string, substring)C, C++ (char * only, returns pointer to first character)returns NULL
std.string.indexOf(string, substring)Dreturns −1
pos(string, substring«, startpos»)Seed7returns 0
strings.Index(string, substring)Goreturns −1
pos(substring, string)Pascal, Object Pascal (Delphi)returns 0
pos(substring, string«,startpos»)Rexxreturns 0
string.find(substring«,startpos»)C++ (STL)returns std::string::npos
string.find(substring«,startpos«,endpos»»)Pythonreturns −1
string.index(substring«,startpos«,endpos»»)raises ValueError
string.index(substring«,startpos»)Rubyreturns nil
string.indexOf(substring«,startpos»)Java, JavaScriptreturns −1
string.IndexOf(substring«,startpos«, charcount»»)VB .NET, C#, Windows PowerShell, F#returns −1
string:str(string, substring)Erlangreturns 0
(string-contains string substring)Scheme (SRFI 13)returns #f
(search substring string)Common Lispreturns NIL
(string-index substring string)ISLISPreturns nil
List.findIndex (List.isPrefixOf substring) (List.tails string)Haskell (returns only index)returns Nothing
Str.search_forward (Str.regexp_string substring) string 0OCamlraises Not_found
Substring.size (#1 (Substring.position substring (Substring.full string)))Standard MLreturns string length
[string rangeOfString:substring].locationObjective-C (NSString * only)returns NSNotFound
string.find(string, substring) (string):find(substring)Luareturns nil
string indexOfSubCollection: substring startingAt: startpos ifAbsent: aBlock string findString: substring startingAt: startposSmalltalk (Squeak, Pharo)evaluate aBlock which is a block closure (or any object understanding value) returns 0
startpos = INDEX(string, substring «,back» «, kind»)Fortranreturns 0 if substring is not in string; returns LEN(string)+1 if substring is empty
POSITION(substring IN string)SQLreturns 0 (positions start at 1)
index(string, substring, startpos )PL/Ireturns 0 (positions start at 1)
index(string, substring, occurrence )Pick Basicreturns 0 if occurrence of substring is not in string; (positions start at 1)
string.indexOf(substring«,startpos«, charcount»»)Cobrareturns −1
string first substring string startposTclreturns −1
(substring⍷string)⍳1APLreturns 1 + the last position in string
string.find(substring)Rustreturns None

Examples

  • Common Lisp (search"e""Hello mate"); returns 1 (search"z""word"); returns NIL
  • C# "Hello mate".IndexOf("e");// returns 1 "Hello mate".IndexOf("e",4);// returns 9 "word".IndexOf("z");// returns -1
  • Raku "Hello, there!".index('e') # returns 1 "Hello, there!".index('z') # returns Nil
  • Scheme (use-modules(srfisrfi-13)) (string-contains"Hello mate""e"); returns 1 (string-contains"word""z"); returns #f
  • Visual Basic ' Examples in InStr("Hello mate","e")' returns 2 InStr(5,"Hello mate","e")' returns 10 InStr("word","z")' returns 0
  • Smalltalk '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

Definitionfind_character(string,char) returns integer
DescriptionReturns the position of the start of the first occurrence of the character char in string. If the character is not found most of these routines return an invalid index value – -1 where indexes are 0-based, 0 where they are 1-based – or some value to be interpreted as Boolean FALSE. This can be accomplished as a special case of #Find, with a string of one character; but it may be simpler or more efficient in many languages to locate just one character. Also, in many languages, characters and strings are different types, so it is convenient to have such a function.
Relatedfind
FormatLanguagesIf not found
char in string(char, pos, string[startpos:])ALGOL 68returns BOOL: TRUE or FALSE, and position in REF INT pos.
instr(string, any char«,startpos») (char, can contain more them one char, in which case the position of the first appearance of any of them is returned.)FreeBASICreturns 0
strchr(string,char)C, C++ (char * only, returns pointer to character)returns NULL
std.string.find(string, dchar)Dreturns −1
string.find(char«,startpos»)C++ (STL)returns std::string::npos
pos(string, char«, startpos»)Seed7returns 0
strings.IndexRune(string,char)Goreturns −1
string.indexOf(char«,startpos»)Java, JavaScriptreturns −1
string.IndexOf(char«,startpos«, charcount»»)VB .NET, C#, Windows PowerShell, F#returns −1
(position char string)Common Lispreturns NIL
(char-index char string)ISLISPreturns nil
List.elemIndex char stringHaskell (returns Just index)returns Nothing
String.index string charOCamlraises Not_found
position = SCAN (string, set «, back» «, kind») position = VERIFY (string, set «, back» «, kind»)[a]Fortranreturns zero
string indexOf: char ifAbsent: aBlock string indexOf: char string includes: charSmalltalkevaluate aBlock which is a BlockClosure (or any object understanding value) returns 0 returns true or false
index(string, char, startpos )PL/Ireturns 0 (positions start at 1)
string.index(?char)Rubyreturns nil
strpos(string,char,startpos)PHPreturns false
string.indexOf(char«,startpos«, charcount»»)Cobrareturns −1
string⍳charAPLreturns 1 + the last position in string
string.find(substring)Rustreturns None

^a Given a set of characters, SCAN returns the position of the first character found, while VERIFY returns the position of the first character that does not belong to the set.

Format

Definitionformat(formatstring, items) returns string
DescriptionReturns the formatted string representation of one or more items.
FormatLanguagesFormat string syntax
associate(file, string); putf(file, $formatstring$, items)ALGOL 68ALGOL
Format(item, formatstring)VB
sprintf(formatstring, items)Perl, PHP, Raku, RubyC
item.fmt(formatstring)RakuC
io_lib:format(formatstring, items)Erlang
sprintf(outputstring, formatstring, items)CC
std::format(formatstring, items)C++ (C++20)Python
std.string.format(formatstring, items)DC
Format(formatstring, items)Object Pascal (Delphi)
fmt.Sprintf(formatstring, items)GoC
printf formatstring itemsUnixC
formatstring % (items)Python, RubyC
formatstring.format(items)Python.NET
fformatstringPython 3
Printf.sprintf formatstringitemsOCaml, F#C
Text.Printf.printf formatstring itemsHaskell (GHC)C
formatstring printf: itemsSmalltalkC
String.format(formatstring, items)JavaC
String.Format(formatstring, items)VB .NET, C#, F#.NET
(format formatstring items)Scheme (SRFI 28)Lisp
(format nil formatstring items)Common LispLisp
(format formatstring items)ClojureLisp
formatstring -f itemsWindows PowerShell.NET
[NSString stringWithFormat:formatstring, items]Objective-C (NSString * only)C
String(format:formatstring, items)Swift (Foundation)C
string.format(formatstring, items) (formatstring):format(items)LuaC
WRITE (outputstring, formatstring) itemsFortranFortran
put string(string) edit(items)(format)PL/IPL/I (similar to Fortran)
String.format(formatstring, items)Cobra.NET
format formatstring itemsTclC
formatnumbers ⍕ items formatstring ⎕FMT itemsAPLAPL
format!(formatstring, items)RustPython

Inequality

Tests if two strings are not equal. See also #Equality.

FormatLanguages
string1 ne string2 string1 NE string2ALGOL 68 – The operator "ne" occurs in bold type-font.
string1 /= string2ALGOL 68, Ada, Erlang, Fortran, Haskell
string1 <> string2BASIC, VB, VB .NET, Pascal, Object Pascal (Delphi), OCaml, PHP, Seed7, Standard ML, F#, COBOL, Cobra, Python 2 (deprecated)
string1 # string2BASIC (some implementations)
string1 ne string2Perl, Raku
(string<> string1 string2)Scheme (SRFI 13)
(string/= string1 string2)Common Lisp
(string/= string1 string2)ISLISP
(not= string1 string2)Clojure
string1 != string2C++ (STL), C#, Go, JavaScript (not similar), PHP (not similar), Python, Ruby, Rust, Swift, D, Mathematica
string1 !== string2JavaScript, PHP
string1 \= string2Rexx
string1 ¬= string2PL/I
test string1 != string2 [ string1 != string2 ]Bourne Shell
string1 -ne string2 -not [string]::Equals(string1, string2)Windows PowerShell
string1 ~= string2Lua, Smalltalk
string1 ≢ string2APL
string1.ne(string2)Rust

index

see #Find

indexof

see #Find

instr

see #Find

instrrev

see #rfind

join

Definitionjoin(separator, list_of_strings) returns a list of strings joined with a separator
DescriptionJoins the list of strings into a new string, with the separator string between each of the substrings. Opposite of split.
Relatedsprintf
FormatLanguages
std.string.join(array_of_strings, separator)D
string:join(list_of_strings, separator)Erlang
join(separator, list_of_strings)Perl, PHP, Raku
implode(separator, array_of_strings)PHP
separator.join(sequence_of_strings)Python, Swift 1.x
array_of_strings.join(separator)Ruby, JavaScript, Raku, Rust
(string-join array_of_strings separator)Scheme (SRFI 13)
(format nil "~{~a~^separator~}" array_of_strings)Common Lisp
(clojure.string/join separator list_of_strings) (apply str (interpose separator list_of_strings))Clojure
strings.Join(array_of_strings, separator)Go
join(array_of_strings, separator)Seed7
String.concat separator list_of_stringsOCaml
String.concatWith separator list_of_stringsStandard ML
Data.List.intercalate separator list_of_stringsHaskell (GHC 6.8+)
Join(array_of_strings, separator)VB
String.Join(separator, array_of_strings)VB .NET, C#, F#
String.join(separator, array_of_strings)Java 8+
&{$OFS=$separator; "$array_of_strings"} array_of_strings -join separatorWindows PowerShell
[array_of_strings componentsJoinedByString:separator]Objective-C (NSString * only)
table.concat(table_of_strings, separator)Lua
{|String streamContents: [ :stream | collectionOfAnything asStringOn: stream delimiter: separator ] collectionOfAnything joinUsing: separatorSmalltalk (Squeak, Pharo)
array_of_strings.join(separator«, final_separator»)Cobra
sequence_of_strings.joinWithSeparator(separator)Swift 2.x
1↓∊separator,¨list_of_stringsAPL

lastindexof

see #rfind

left

Definitionleft(string,n) returns string
DescriptionReturns the left n part of a string. If n is greater than the length of the string then most implementations return the whole string (exceptions exist – see code examples). For variable-length encodings such as UTF-8, UTF-16 or Shift-JIS, it can be necessary to remove string positions at the end, to avoid invalid strings.
FormatLanguages
string (string'First .. string'First + n - 1)Ada
substr(string, 0, n)AWK (changes string), Perl, PHP, Raku
LEFT$(string,n)BASIC, VB
left(string,n)VB, FreeBASIC, Ingres, Pick Basic
strncpy(string2, string, n)C standard library
string.substr(0,n)C++ (STL), Raku
[string substringToIndex:n]Objective-C (NSString * only)
(apply str (take n string))Clojure
string[0 .. n]D
string:substr(string, start, length)Erlang
(subseq string 0 n)Common Lisp
string[:n]Cobra, Go, Python
left(string,n «,padchar»)Rexx, Erlang
string[0, n] string[0..n - 1]Ruby
string[1, n]Pick Basic
string[ .. n]Seed7
string.Substring(0,n)VB .NET, C#, Windows PowerShell, F#
leftstr(string, n)Pascal, Object Pascal (Delphi)
copy (string,1,n)Turbo Pascal
string.substring(0,n)Java, JavaScript
(string-take string n)Scheme (SRFI 13)
take n stringHaskell
String.extract (string, n, NONE)Standard ML
String.sub string 0 nOCaml
string.[..n]F#
string.sub(string, 1, n) (string):sub(1, n)Lua
string first: nSmalltalk (Squeak, Pharo)
string(:n)Fortran
StringTake[string, n]Mathematica
string («FUNCTION» LENGTH(string) - n:n)COBOL
string.substring(0, n)Cobra
n↑string.APL
string[0..n] string[..n] string.get(0..n) string.get(..n)Rust

len

see #length

length

Definitionlength(string) returns an integer number
DescriptionReturns the length of a string (not counting the null terminator or any other of the string's internal structural information). An empty string returns a length of 0.
FormatReturnsLanguages
string'LengthAda
UPB stringALGOL 68
echo "${#string_param}"Bash
length(string)Ingres, Perl 5, Pascal, Object Pascal (Delphi), Rexx, Seed7, SQL, PL/I
len(string)BASIC, FreeBASIC, Python, Go, Pick Basic
length(string), string:len(string)Erlang
Len(string)VB, Pick Basic
string.LengthNumber of UTF-16 code unitsVB .NET, C#, Windows PowerShell, F#
chars(string) string.charsNumber of graphemes (NFG)Raku
codes(string) string.codesNumber of Unicode code pointsRaku
string.size OR string.lengthNumber of bytesRuby
strlen(string)Number of bytesC, PHP
string.length()C++ (STL)
string.lengthCobra, D, JavaScript
string.length()Number of UTF-16 code unitsJava
(string-length string)Scheme
(length string)Common Lisp, ISLISP
(count string)Clojure
String.length stringOCaml
size stringStandard ML
length stringNumber of Unicode code pointsHaskell
string.lengthNumber of UTF-16 code unitsObjective-C (NSString * only)
string.characters.countNumber of charactersSwift (2.x)
count(string)Number of charactersSwift (1.2)
countElements(string)Number of charactersSwift (1.0–1.1)
string.len(string) (string):len() #stringLua
string sizeSmalltalk
LEN(string) LEN_TRIM(string)Fortran
StringLength[string]Mathematica
«FUNCTION» LENGTH(string) or «FUNCTION» BYTE-LENGTH(string)number of characters and number of bytes, respectivelyCOBOL
string length stringa decimal string giving the number of charactersTcl
≢ stringAPL
string.len()Number of bytesRust
string.chars().count()Number of Unicode code pointsRust

locate

see #Find

Lowercase

Definitionlowercase(string) returns string
DescriptionReturns the string in lower case.
FormatLanguages
LCase(string)VB
lcase(string)FreeBASIC
lc(string)Perl, Raku
string.lcRaku
tolower(char)C
std.string.toLower(string)D
transform(string.begin(), string.end(), result.begin(), ::tolower)C++
lowercase(string)Object Pascal (Delphi)
strtolower(string)PHP
lower(string)Seed7
${string_param,,}Bash
echo "string" | tr 'A-Z' 'a-z'Unix
string.lower()Python
downcase(string)Pick Basic
string.downcaseRuby
strings.ToLower(string)Go
(string-downcase string)Scheme (R6RS), Common Lisp
(lower-case string)Clojure
String.lowercase stringOCaml
String.map Char.toLower stringStandard ML
map Char.toLower stringHaskell
string.toLowerCase()Java, JavaScript
to_lower(string)Erlang
string.ToLower()VB .NET, C#, Windows PowerShell, F#
string.lowercaseStringObjective-C (NSString * only), Swift (Foundation)
string.lower(string) (string):lower()Lua
string asLowercaseSmalltalk
LOWER(string)SQL
lowercase(string)PL/I
ToLowerCase[string]Mathematica
«FUNCTION» LOWER-CASE(string)COBOL
string.toLowerCobra
string tolower stringTcl
string.to_lowercase()Rust

mid

see #substring

partition

Definition<string>.partition(separator) returns the sub-string before the separator; the separator; then the sub-string after the separator.
DescriptionSplits the given string by the separator and returns the three substrings that together make the original.
FormatLanguagesComments
string.partition(separator)Python, Ruby(1.9+)
lists:partition(pred, string)Erlang
split /(separator)/, string, 2Perl 5
split separator, string, 2 string.split( separator, 2 )RakuSeparator does not have to be a regular expression

replace

Definitionreplace(string, find, replace) returns string
DescriptionReturns a string with find occurrences changed to replace.
FormatLanguages
changestr(find, string, replace)Rexx
std.string.replace(string, find, replace)D
Replace(string, find, replace)VB
replace(string, find, replace)Seed7
change(string, find, replace)Pick Basic
string.Replace(find, replace)C#, F#, VB .NET
str_replace(find, replace, string)PHP
re:replace(string, find, replace, «{return, list}»)Erlang
string.replace(find, replace)Cobra, Java (1.5+), Python, Rust
string.replaceAll(find_regex, replace)Java
string.gsub(find, replace)Ruby
string =~ s/find_regex/replace/gPerl 5
string.subst(find, replace, :g)Raku
string.replace(find, replace, "g") string.replace(/find_regex/g, replace)JavaScript
echo "string" | sed 's/find_regex/replace/g'Unix
${string_param//find_pattern/replace}Bash
string.replace(find, replace) string -replace find_regex, replaceWindows PowerShell
Str.global_replace (Str.regexp_string find) replace stringOCaml
[string stringByReplacingOccurrencesOfString:find withString:replace]Objective-C (NSString * only)
string.stringByReplacingOccurrencesOfString(find, withString:replace)Swift (Foundation)
string.gsub(string, find, replace) (string):gsub(find, replace)Lua
string copyReplaceAll: find with: replaceSmalltalk (Squeak, Pharo)
string map {find replace} stringTcl
StringReplace[string, find -> replace]Mathematica
strings.Replace(string, find, replace, -1)Go
INSPECT string REPLACING ALL/LEADING/FIRST find BY replaceCOBOL
find_regex ⎕R replace_regex ⊢ stringAPL

reverse

Definitionreverse(string)
DescriptionReverses the order of the characters in the string.
FormatLanguages
reverse stringPerl 5, Haskell
flip string string.flipRaku
lists:reverse(string)Erlang
strrev(string)PHP
string[::-1]Python
(string-reverse string)Scheme (SRFI 13)
(reverse string)Common Lisp
string.reverseRuby, D (modifies string)
new StringBuilder(string).reverse().toString()Java
std::reverse(string.begin(), string.end());C++ (std::string only, modifies string)
StrReverse(string)VB
string.Reverse()VB .NET, C#
implode (rev (explode string))Standard ML
string.split("").reverse().join("")JavaScript
string.reverse(string) (string):reverse()Lua
string reverseSmalltalk
StringReverse[string]Mathematica
reverse(string)PL/I
«FUNCTION» REVERSE(string)COBOL
string.toCharArray.toList.reversed.join()Cobra
String(string.characters.reverse())Swift (2.x)
String(reverse(string))Swift (1.2)
string reverse stringTcl
⌽stringAPL
string.chars().rev().collect::<String>()Rust
echo string | revUnix

rfind

Definitionrfind(string,substring) returns integer
DescriptionReturns the position of the start of the last occurrence of substring in string. If the substring is not found most of these routines return an invalid index value – -1 where indexes are 0-based, 0 where they are 1-based – or some value to be interpreted as Boolean FALSE.
Relatedinstr
FormatLanguagesIf not found
InStrRev(«startpos,» string,substring)VBreturns 0
instrrev(«startpos,» string,substring)FreeBASICreturns 0
rindex(string,substring«,startpos»)Perl 5returns −1
rindex(string,substring«,startpos») string.rindex(substring«,startpos»)Rakureturns Nil
strrpos(string,substring«,startpos»)PHPreturns FALSE
string.rfind(substring«,startpos»)C++ (STL)returns std::string::npos
std.string.rfind(string, substring)Dreturns −1
string.rfind(substring«,startpos«, endpos»»)Pythonreturns −1
string.rindex(substring«,startpos«, endpos»»)raises ValueError
rpos(string, substring«,startpos»)Seed7returns 0
string.rindex(substring«,startpos»)Rubyreturns nil
strings.LastIndex(string, substring)Goreturns −1
string.lastIndexOf(substring«,startpos»)Java, JavaScriptreturns −1
string.LastIndexOf(substring«,startpos«, charcount»»)VB .NET, C#, Windows PowerShell, F#returns −1
(search substring string :from-end t)Common Lispreturns NIL
[string rangeOfString:substring options:NSBackwardsSearch].locationObjective-C (NSString * only)returns NSNotFound
Str.search_backward (Str.regexp_string substring) string (Str.length string - 1)OCamlraises Not_found
string.match(string, '.*()'..substring) string:match('.*()'..substring)Luareturns nil
Ada.Strings.Unbounded.Index(Source => string, Pattern => substring, Going => Ada.Strings.Backward)Adareturns 0
string.lastIndexOf(substring«,startpos«, charcount»»)Cobrareturns −1
string lastIndexOfString:substringSmalltalkreturns 0
string last substring string startposTclreturns −1
(⌽<\⌽substring⍷'string')⍳1APLreturns −1
string.rfind(substring)Rustreturns None

right

Definitionright(string,n) returns string
DescriptionReturns the right n part of a string. If n is greater than the length of the string then most implementations return the whole string (exceptions exist – see code examples).
FormatLanguages
string (string'Last - n + 1 .. string'Last)Ada
Right(string,n)VB
RIGHT$(string,n)BASIC
right(string,n)FreeBASIC, Ingres, Pick Basic
strcpy(string2, string+n) (n must not be greater than the length of string)C
string.Substring(string.Length()-n)C#
string[len(string)-n:]Go
string.substring(string.length()-n)Java
string.slice(-n)JavaScript
right(string,n «,padchar»)Rexx, Erlang
substr(string,-n)Perl 5, PHP
substr(string,*-n) string.substr(*-n)Raku
string[-n:]Cobra, Python
${string_param: -n} (a space occurs after the colon)Bash
string[n]Pick Basic
(string-take-right string n)Scheme (SRFI 13)
string[-n..-1]Ruby
string[$-n .. $]D
String.sub string (String.length string - n) nOCaml
string.sub(string, -n) (string):sub(-n)Lua
string last: nSmalltalk (Squeak, Pharo)
StringTake[string, -n]Mathematica
string (1:n)COBOL
¯n↑string.APL
string[n..] string.get(n..)Rust

rpartition

Definition<string>.rpartition(separator) Searches for the separator from right-to-left within the string then returns the sub-string before the separator; the separator; then the sub-string after the separator.
DescriptionSplits the given string by the right-most separator and returns the three substrings that together make the original.
FormatLanguages
string.rpartition(separator)Python, Ruby

slice

see #substring

split

Definition<string>.split(separator[, limit]) splits a string on separator, optionally only up to a limited number of substrings
DescriptionSplits the given string by occurrences of the separator (itself a string) and returns a list (or array) of the substrings. If limit is given, after limit – 1 separators have been read, the rest of the string is made into the last substring, regardless of whether it has any separators in it. The Scheme and Erlang implementations are similar but differ in several ways. JavaScript differs also in that it cuts, it does not put the rest of the string into the last element. . The Cobra implementation will default to whitespace. Opposite of join.
FormatLanguages
split(/separator/, string«, limit»)Perl 5
split(separator, string«, limit») string.split(separator, «limit»)Raku
explode(separator, string«, limit»)PHP
string.split(separator«, limit-1»)Python
string.split(separator«, limit»)JavaScript, Java, Ruby
string:tokens(string, sepchars)Erlang
strings.Split(string, separator) strings.SplitN(string, separator, limit)Go
(string-tokenize string« charset« start« end»»»)Scheme (SRFI 13)
Split(string, sepchars«, limit»)VB
string.Split(sepchars«, limit«, options»»)VB .NET, C#, F#
string -split separator«, limit«, options»»Windows PowerShell
Str.split (Str.regexp_string separator) stringOCaml
std.string.split(string, separator)D
[string componentsSeparatedByString:separator]Objective-C (NSString * only)
string.componentsSeparatedByString(separator)Swift (Foundation)
TStringList.Delimiter, TStringList.DelimitedTextObject Pascal
StringSplit[string, separator«, limit»]Mathematica
string.split«(sepchars«, limit«, options»»)»Cobra
split string separatorTcl
(separator≠string)⊂string in APL2 separator(≠⊆⊢)string in Dyalog APL 16.0APL
string.split(separator) string.split(limit, separator)Rust

sprintf

see #Format

strip

see #trim

strcmp

see #Compare (integer result)

substring

Definitionsubstring(string, startpos, endpos) returns string substr(string, startpos, numChars) returns string
DescriptionReturns a substring of string between starting at startpos and endpos, or starting at startpos of length numChars. The resulting string is truncated if there are fewer than numChars characters beyond the starting point. endpos represents the index after the last character in the substring. For variable-length encodings such as UTF-8, UTF-16 or Shift-JIS, it can be necessary to remove string positions at the end, to avoid invalid strings.
FormatLanguages
string[startpos:endpos]ALGOL 68 (changes base index)
string (startpos .. endpos)Ada (changes base index)
Mid(string, startpos, numChars)VB
mid(string, startpos, numChars)FreeBASIC
string[startpos+(⍳numChars)-~⎕IO]APL
MID$(string, startpos, numChars)BASIC
substr(string, startpos, numChars)AWK (changes string), Perl 5, PHP
substr(string, startpos, numChars) string.substr(startpos, numChars)Raku
substr(string, startpos «,numChars, padChar»)PL/I
substr(string, startpos «,numChars, padChar»)Rexx
string[startpos:endpos]Cobra, Python, Go
string[startpos, numChars]Pick Basic
string[startpos, numChars] string[startpos .. endpos-1] string[startpos ... endpos]Ruby
string[startpos .. endpos] string[startpos len numChars]Seed7
string.slice(startpos«, endpos»)JavaScript
string.substr(startpos«, numChars»)C++ (STL), JavaScript
string.Substring(startpos, numChars)VB .NET, C#, Windows PowerShell, F#
string.substring(startpos«, endpos»)Java, JavaScript
copy(string, startpos, numChars)Object Pascal (Delphi)
(substring string startpos endpos)Scheme
(subseq string startpos endpos)Common Lisp
(subseq string startpos endpos)ISLISP
String.sub string startpos numCharsOCaml
substring (string, startpos, numChars)Standard ML
string:sub_string(string, startpos, endpos) string:substr(string, startpos, numChars)Erlang
strncpy(result, string + startpos, numChars);C
string[startpos .. endpos+1]D
take numChars $ drop startpos stringHaskell
[string substringWithRange:NSMakeRange(startpos, numChars)]Objective-C (NSString * only)
string.[startpos..endpos]F#
string.sub(string, startpos, endpos) (string):sub(startpos, endpos)Lua
string copyFrom: startpos to: endposSmalltalk
string(startpos:endpos)Fortran
SUBSTRING(string FROM startpos «FOR numChars»)SQL
StringTake[string, {startpos, endpos}]Mathematica
string (startpos:numChars)COBOL
${string_param:startpos:numChars}Bash
string range string startpos endposTcl
string[startpos..endpos] string.get(startpos..endpos)Rust

Uppercase

Definitionuppercase(string) returns string
DescriptionReturns the string in upper case.
FormatLanguages
UCase(string)VB
ucase(string)FreeBASIC
toupper(string)AWK (changes string)
uc(string)Perl, Raku
string.ucRaku
toupper(char)C (operates on one character)
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);C (string / char array)
std.string.toUpper(string)D
transform(string.begin(), string.end(), result.begin(), toupper)C++
uppercase(string)Object Pascal (Delphi)
upcase(char)Object Pascal (Delphi) (operates on one character)
strtoupper(string)PHP
upper(string)Seed7
${string_param^^} (mnemonic: ^ is pointing up)Bash
echo "string" | tr 'a-z' 'A-Z'Unix
translate(string) UPPER variables PARSE UPPER VAR SrcVar DstVarRexx
string.upper()Python
upcase(string)Pick Basic
string.upcaseRuby
strings.ToUpper(string)Go
(string-upcase string)Scheme, Common Lisp
String.uppercase stringOCaml
String.map Char.toUpper stringStandard ML
map Char.toUpper stringHaskell
string.toUpperCase()Java, JavaScript
string.uppercase()Kotlin
to_upper(string)Erlang
string.ToUpper()VB .NET, C#, Windows PowerShell, F#
string.uppercaseStringObjective-C (NSString * only), Swift (Foundation)
string.upper(string) (string):upper()Lua
string asUppercaseSmalltalk
UPPER(string)SQL
ToUpperCase[string]Mathematica
«FUNCTION» UPPER-CASE(string)COBOL
string.toUpperCobra
string toupper stringTcl
string.to_uppercase()Rust

trim

trim or strip is used to remove whitespace from the beginning, end, or both beginning and end, of a string.

Example usageLanguages
String.Trim([chars])C#, VB.NET, Windows PowerShell
string.strip();D
(.trim string)Clojure
sequence [ predicate? ] trimFactor
(string-trim '(#\Space #\Tab #\Newline) string)Common Lisp
(string-trim string)Scheme
string.trim()Java, JavaScript (1.8.1+, Firefox 3.5+), Rust
Trim(String)Pascal, QBasic, Visual Basic, Delphi
string.strip()Python
strings.Trim(string, chars)Go
LTRIM(RTRIM(String))Oracle SQL, T-SQL
strip(string [,option, char])REXX
string:strip(string [,option, char])Erlang
string.strip string.lstrip string.rstripRuby
string.trimRaku
trim(string)PHP, Raku
[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]Objective-C using Cocoa
string withBlanksTrimmed string withoutSpaces string withoutSeparatorsSmalltalk (Squeak, Pharo) Smalltalk
strip(string)SAS
string trim $stringTcl
TRIM(string) TRIM(ADJUSTL(string))Fortran
TRIM(string)SQL
TRIM(string) LTrim(string) RTrim(String)ColdFusion
String.trim stringOCaml 4+

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

APL can use regular expressions directly:

Alternatively, a functional approach combining Boolean masks that filter away leading and trailing spaces:

Or reverse and remove leading spaces, twice:

AWK

In AWK, one can use regular expressions to trim:

or:

C/C++

There is no standard trim function in C or C++. Most of the available string libraries 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:

The open source C++ library Boost has several trim variants, including a standard one:

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:

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.

Haskell

A trim algorithm in Haskell:

may be interpreted as follows: f drops the preceding whitespace, and reverses the string. f is then again applied to its own output. The type signature (the second line) is optional.

J

The trim algorithm in J is a functional description:

That is: filter (#~) for non-space characters (' '&~:) between leading (+./\) and (*.) trailing (+./\.) spaces.

JavaScript

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:

Perl

Perl 5 has no built-in trim function. However, the functionality is commonly achieved using regular expressions.

Example:

or:

These examples modify the value of the original variable $string.

Also available for Perl is StripLTSpace in String::Strip from CPAN.

There are, however, two functions that are commonly used to strip whitespace from the end of strings, chomp and chop:

  • removes the last character from a string and returns it.
  • removes the trailing newline character(s) from a string if present. (What constitutes a newline is dependent).

In Raku, the upcoming sister language of Perl, strings have a trim method.

Example:

Tcl

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

Example of trimming vowels:

XSLT

XSLT includes the function normalize-space(string) which strips leading and trailing whitespace, in addition to replacing any whitespace sequence (including line breaks) with one space.

Example:

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.