Comparison of programming languages (string functions)


String functions are used in computer programming languages to manipulate a string or query information about a string.[]
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, 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, 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 function. This function returns the length of a string literal.
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. 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. Note, string concatenation and regular expressions are handled in separate pages. Statements in guillemets are optional.

CharAt

DefinitioncharAt returns character.
DescriptionReturns character at index in the string.
EquivalentSee [|substring] of length 1 character.


var
MyStr: string = 'Hello, World';
MyChar: Char;
begin
MyChar := MyStr; // 'e'


  1. Example in ALGOL 68 #
"Hello, World"; // 'e'


// Example in C# and Ya
"Hello, World"; // 'l'


  1. Example in Perl 5
substr; # 'e'


  1. Examples in Python
"Hello, World" # 'l'
"Hello, World" # 'r'


  1. Example in Raku
"Hello, World".substr; # 'e'


' Example in Visual Basic
Mid


' Example in Visual Basic.NET
"Hello, World".Chars ' "l"c


" Example in Smalltalk "
'Hello, World' at: 2. "$e"


//Example in Rust
"Hello, World".chars.nth; //'l'

Compare (integer result)

FormatLanguages
IF string1<string2 THEN -1 ELSE ABS FIALGOL 68
cmpPython 2
- Python
strcmpC, PHP
std.string.cmpD
StrCompVB, Object Pascal
string1 cmp string2Perl, Raku
string1 compare: string2Smalltalk
string1 <=> string2Ruby
string1.compareC++, Swift
compareRexx, Seed7
CompareStrPascal, Object Pascal
string1.compareToCobra, Java
string1.CompareToVB.NET, C#, F#
Clojure
Common Lisp
Scheme
ISLISP
compare string1 string2OCaml
String.compare Standard ML
compare string1 string2Haskell
::CompareWindows PowerShell
Objective-C
LLT
LLE
LGT
LGE
Fortran
string1.localeCompareJavaScript
bytes.Compare, byte)Go
string compare ?-nocase? ?-length int? string1 string2Tcl
comparePL/I


  1. Example in Perl 5
"hello" cmp "world"; # returns -1


  1. Example in Python
cmp # returns -1


  1. Examples in Raku
"hello" cmp "world"; # returns Less
"world" cmp "hello"; # returns More
"hello" cmp "hello"; # returns Same


/** Example in Rexx */
compare /* returns index of mismatch: 1 */


; Example in Scheme
; returns index of mismatch: 0

Compare (relational operator-based, Boolean result)

FormatLanguages
string1 OP string2, where OP can be any of =, <>, <, >, <= and >=Pascal, Object Pascal, 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
, where OP can be any of =, -ci=, <, -ci<, >, -ci>, <=, -ci<=, >= and -ci>= Scheme
, where OP can be any of =, -ci=, <>, -ci<>, <, -ci<, >, -ci>, <=, -ci<=, >= and -ci>= Scheme
, where OP can be any of =, -equal, /=, -not-equal, <, -lessp, >, -greaterp, <=, -not-greaterp, >= and -not-lessp Common Lisp
, 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++, C#, D, Go, JavaScript, Python, PHP, Ruby, Swift, Ya
string1 OP string2, where OP can be any of -eq, -ceq, -ne, -cne, -lt, -clt, -gt, -cgt, -le, -cle, -ge, and -cge 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 function.C, Java


% Example in Erlang
"hello" > "world". % returns false


  1. Example in Raku
"art" gt "painting"; # returns False
"art" lt "painting"; # returns True


  1. Example in Windows PowerShell
"hello" -gt "world" # returns false


;; Example in Common Lisp
; returns nil
; returns non nil

Concatenation

Definitionconcatenate returns string.
DescriptionConcatenates two strings to each other, returning the combined string. Note that 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 & string2Ada, FreeBASIC, Seed7, BASIC, VB, VB.NET, COBOL
strcatC, C++
string1. string2Perl, PHP
string1 + string2ALGOL 68, C++, C#, Cobra, FreeBASIC, Go, Pascal, Object Pascal, Java, JavaScript, Windows PowerShell, Python, Ruby, Rust, F#, Swift, Turing, VB, Ya
string1 ~ string2D, Raku
Scheme, ISLISP
Common Lisp
Clojure
string1 || string2Rexx, SQL, PL/I
string1 // string2Fortran
string1 ++ string2Erlang, Haskell
string1 ^ string2OCaml, Standard ML, F#
Objective-C
string1.. string2Lua
string1, string2Smalltalk, APL
string1 string2SNOBOL
string1string2Bash shell
string1 <> string2Mathematica
concat string1 string2Tcl


'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
; returns "abc def ghi"


  1. Example in Perl 5
"abc" ~ "def"; # returns "abcdef"
"Perl " ~ 5; # returns "Perl 5"


  1. Example in Raku
"abc" ~ "def"; # returns "abcdef"
"Perl " ~ 6; # returns "Raku"

Contains

Definitioncontains 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

¢ Example in ALGOL 68 ¢
string in string; ¢ returns true ¢
string in string; ¢ returns false ¢

// Example In C#
"Hello mate".Contains; // returns true
"word".Contains; // returns false


  1. Example in Python
"e" in "Hello mate" # returns true
"z" in "word" # returns false


  1. Example in Raku
"Good morning!".contains # returns False
"¡Buenos días!".contains; # returns True


" Example in Smalltalk "
'Hello mate' includesSubstring: 'e' " returns true "
'word' includesSubstring: 'z' " returns false "

Equality

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".
FormatLanguages
string1 string2Python, C++, C#, Cobra, Go, JavaScript, PHP, Ruby, Erlang, Haskell, Lua, D, Mathematica, Swift, Ya
string1 string2JavaScript, PHP
string1 string2 or
string1.EQ. string2
Fortran
strcmp 0C
Scheme
Common Lisp, ISLISP
string1 = string2ALGOL 68, Ada, Object Pascal, OCaml, Pascal, Rexx, Seed7, Standard ML, BASIC, VB, VB.NET, F#, Smalltalk, PL/I, COBOL
test string1 = string2, or
Bourne Shell
string1 eq string2Perl, Raku
string1.equalsCobra, Java
string1.EqualsC#
string1 -eq string2, or
::Equals
Windows PowerShell
, or
Objective-C
string1string2APL


// Example in C#
"hello" "world" // returns false


' Example in Visual Basic
"hello" = "world" ' returns false


  1. Examples in Perl 5
'hello' eq 'world' # returns 0
'hello' eq 'hello' # returns 1


  1. Examples in Raku
'hello' eq 'world' # returns False
'hello' eq 'hello' # returns True


  1. Example in Windows PowerShell
"hello" -eq "world" # returns false


⍝ Example in APL
'hello' ≡ 'world' ⍝ returns 0

Find

Definitionfind 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


; Examples in Common Lisp
; returns 1
; returns NIL


// Examples in C#
"Hello mate".IndexOf; // returns 1
"Hello mate".IndexOf; // returns 9
"word".IndexOf; // returns -1


  1. Examples in Raku
"Hello, there!".index # returns 1
"Hello, there!".index # returns Nil


; Examples in Scheme
; returns 1
; returns #f


' Examples in Visual Basic
InStr ' returns 2
InStr ' returns 10
InStr ' returns 0


" Examples in Smalltalk "
'Hello mate' indexOfSubCollection:'ate' "returns 8"
'Hello mate' indexOfSubCollection:'late' "returns 0"
I'Hello mate'
indexOfSubCollection:'late'
ifAbsent: "returns 99"
'Hello mate'
indexOfSubCollection:'late'
ifAbsent: "raises an exception"

Find character

Definitionfind_character 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


// Examples in C#
"Hello mate".IndexOf; // returns 1
"word".IndexOf // returns -1


; Examples in Common Lisp
; returns 1
; returns NIL

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 returns string
DescriptionReturns the formatted string representation of one or more items.


// Example in C#
String.Format; // returns "My pen costs $19.99"


// Example in Object Pascal
Format; // returns "My pen costs $19.99"


// Example in Java
String.format; // returns "My pen costs $19.99"


  1. Examples in Raku
sprintf "My %s costs \$%.2f", "pen", 19.99; # returns "My pen costs $19.99"
1.fmt; # returns "0001"


  1. Example in Python
"My %s costs $%.2f" % ; # returns "My pen costs $19.99"
"My costs $".format; # returns "My pen costs $19.99"


; Example in Scheme
; returns "My pen costs $19.99"


/* example in PL/I */
put string edit
/* returns "My pen costs $19.99" */

Inequality

Tests if two strings are not equal. See also #Equality.
FormatLanguages
string1 ne string2, or string1 NE string2ALGOL 68 – note: the operator "ne" is literally in bold type-font.
string1 /= string2ALGOL 68, Ada, Erlang, Fortran, Haskell
string1 <> string2BASIC, VB, VB.NET, Pascal, Object Pascal, OCaml, PHP, Seed7, Standard ML, F#, COBOL, Cobra, Python 2
string1 # string2BASIC
string1 ne string2Perl, Raku
Scheme
Common Lisp
ISLISP
Clojure
string1 != string2C++, C#, Go, JavaScript, PHP, Python, Ruby, Swift, D, Mathematica
string1 ! string2JavaScript, PHP
string1 \= string2Rexx
string1 ¬= string2PL/I
test string1 != string2, or
Bourne Shell
string1 -ne string2, or
-not ::Equals
Windows PowerShell
string1 ~= string2Lua, Smalltalk
string1string2APL


// Example in C#
"hello" != "world" // returns true


' Example in Visual Basic
"hello" <> "world" ' returns true


;; Example in Clojure
; ⇒ true


  1. Example in Perl 5
'hello' ne 'world' # returns 1


  1. Example in Raku
'hello' ne 'world' # returns True


  1. Example in Windows PowerShell
"hello" -ne "world" # returns true

index

see #Find

indexof

see #Find

instr

see #Find

instrrev

see #rfind

join

FormatLanguages
std.string.joinD
string:joinErlang
joinPerl, PHP, Raku
implodePHP
separator.joinPython, Swift 1.x
array_of_strings.joinRuby, JavaScript, Raku
Scheme
Common Lisp

Clojure
strings.JoinGo
joinSeed7
String.concat separator list_of_stringsOCaml
String.concatWith separator list_of_stringsStandard ML
Data.List.intercalate separator list_of_stringsHaskell
JoinVB
String.JoinVB.NET, C#, F#
String.joinJava 8+
&, or
array_of_strings -join separator
Windows PowerShell
Objective-C
table.concatLua

lastindexof

see #rfind

left

FormatLanguages
string Ada
substrAWK, Perl, PHP, Raku
LEFT$BASIC, VB
leftVB, FreeBASIC, Ingres, Pick Basic
strncpyC standard library
string.substrC++, Raku
Objective-C
Clojure
stringD
string:substrErlang
Common Lisp
stringCobra, Go, Python
leftRexx, Erlang
string
string
Ruby
stringPick Basic
stringSeed7
string.SubstringVB.NET, C#, Windows PowerShell, F#
leftstrPascal, Object Pascal
copy Turbo Pascal
string.substringJava, JavaScript
Scheme
take n stringHaskell
String.extract Standard ML
String.sub string 0 nOCaml
string.F#
string.sub
:sub
Lua
string first: nSmalltalk
stringFortran
StringTakeMathematica
string COBOL
string.substringCobra
nstring.APL


  1. Example in Raku
"Hello, there!".substr; # returns "Hello,"


/* Examples in Rexx */
left /* returns "abc" */
left /* returns "abcde " */
left /* returns "abcde***" */


; Examples in Scheme
; returns "abc"
; error


' Examples in Visual Basic
Left ' returns "san"
Left ' returns "sandroguidi"


// Examples in Ya
"abcde" // returns "abc"
"abcde" // returns "abcde"

len

see #length

length

FormatReturnsLanguages-
string'LengthAda-
UPB stringALGOL 68-
lengthIngres, Perl 5, Pascal, Object Pascal, Rexx, Seed7, SQL, PL/I-
lenBASIC, FreeBASIC, Python, Go, Pick Basic-
length, string:lenErlang-
LenVB, Pick Basic-
string.LengthNumber of 16-bit UTF-16-encoded blocksVB.NET, C#, Windows PowerShell, F#-
chars
string.chars
Number of graphemes Raku-
codes
string.codes
Number of Unicode code pointsRaku-
string.size OR string.lengthNumber of bytesRuby-
strlenNumber of bytesC, PHP-
string.lengthC++ -
string.lengthCobra, D, JavaScript-
string.lengthNumber of 16-bit UTF-16-encoded blocksJava-
Scheme-
Common Lisp, ISLISP-
Clojure-
String.length stringOCaml-
size stringStandard ML-
length stringNumber of Unicode codepointsHaskell-
string.lengthNumber of 16-bit UTF-16-encoded blocksObjective-C -
string.characters.countNumber of charactersSwift -
countNumber of charactersSwift -
countElementsNumber of charactersSwift -
string.len
:len
#string
Lua-
string sizeSmalltalk-
LEN, or LEN_TRIMFortran-
StringLengthMathematica-
Length or
Size
number of bytes as $int+Ya-
«FUNCTION» LENGTH or
«FUNCTION» BYTE-LENGTH
number of characters and number of bytes, respectivelyCOBOL-
string length stringa decimal string giving the number of charactersTcl-
stringAPL


// Examples in C#
"hello".Length; // returns 5
"".Length; // returns 0


  1. Examples in Erlang
string:len. % returns 5
string:len. % returns 0


  1. Examples in Perl 5
length; # returns 5
length; # returns 0


  1. 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 ' returns 5
Len ' returns 0


//Examples in Objective-C
//returns 5
//returns 0


-- Examples in Lua
:len -- returns 5
  1. "" -- returns 0

locate

see #Find

Lowercase

Definitionlowercase returns string
DescriptionReturns the string in lower case.


// Example in C#
"Wiki means fast?".ToLower; // "wiki means fast?"


; Example in Scheme
; "wiki means fast?"


/* Example in C */
  1. include
  2. include
int main


  1. Example in Raku
"Wiki means fast?".lc; # "wiki means fast?"

mid

see #substring

partition

FormatLanguagesComments
string.partitionPython, Ruby
lists:partitionErlang
split //, string, 2Perl 5
split separator, string, 2
string.split
RakuSeparator does not have to be a regular expression


  1. Examples in Python
"Spam eggs spam spam and ham".partition #
"Spam eggs spam spam and ham".partition #


  1. Examples in Perl 5 / Raku
split //, 'Spam eggs spam spam and ham',2; # ;
split //, 'Spam eggs spam spam and ham',2; # ;

replace

FormatLanguages
changestrRexx
std.string.replaceD
ReplaceVB
replaceSeed7
changePick Basic
string.ReplaceVB.NET, C#, F#
str_replacePHP
re:replaceErlang
string.replaceCobra, Python, Java
string.replaceAllJava
string.gsubRuby
string =~ s/find_regex/replace/gPerl 5
string.substRaku
string.replace or
string.replace
JavaScript
echo "string" | sed 's/find_regex/replace/g'Unix
string.replace, or
string -replace find_regex, replace
Windows PowerShell
Str.global_replace replace stringOCaml
Objective-C
string.stringByReplacingOccurrencesOfStringSwift
string.gsub
:gsub
Lua
string copyReplaceAll: find with: replaceSmalltalk
string map stringTcl
StringReplaceMathematica
strings.ReplaceGo
INSPECT string REPLACING ALL/LEADING/FIRST find BY replaceCOBOL
find_regex ⎕R replace_regexstringAPL


// Examples in C#
"effffff".Replace; // returns "ejumpjumpjumpjumpjumpjump"
"blah".Replace; // returns "blah"


// Examples in Java
"effffff".replace; // returns "ejumpjumpjumpjumpjumpjump"
"effffff".replaceAll; // returns "ejump"


// Examples in Raku
"effffff".subst; # returns "ejumpjumpjumpjumpjumpjump"
"blah".subst; # returns "blah"


' Examples in Visual Basic
Replace ' returns "ejumpjumpjumpjumpjumpjump"
Replace ' returns "blah"


  1. Examples in Windows PowerShell
"effffff" -replace "f", "jump" # returns "ejumpjumpjumpjumpjumpjump"
"effffff" -replace "f*", "jump" # returns "ejump"

reverse

FormatLanguages
reverse stringPerl 5, Haskell
flip string
string.flip
Raku
lists:reverseErlang
strrevPHP
stringPython
Scheme
Common Lisp
string.reverseRuby, D
new StringBuilder.reverse.toStringJava
std::reverse, string.end);C++
StrReverseVB
string.Reverse.ToStringVB.NET, C#
implode Standard ML
string.split.reverse.joinJavaScript
string.reverse
:reverse
Lua
string reverseSmalltalk
StringReverseMathematica
reversePL/I
«FUNCTION» REVERSECOBOL
string.toCharArray.toList.reversed.joinCobra
String)Swift
StringSwift
string reverse stringTcl
stringAPL


" Example in Smalltalk "
'hello' reversed " returns 'olleh' "


  1. Example in Perl 5
reverse "hello" # returns "olleh"


  1. Example in Raku
"hello".flip # returns "olleh"


  1. Example in Python
"hello" # returns "olleh"


; Example in Scheme
; returns "olleh"

rfind

Definitionrfind 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


; Examples in Common Lisp
; returns 9
; returns NIL


// Examples in C#
"Hello mate".LastIndexOf; // returns 9
"Hello mate".LastIndexOf; // returns 1
"word".LastIndexOf; // returns -1


  1. Examples in Perl 5
rindex; # returns 9
rindex; # returns 1
rindex; # returns -1


  1. Examples in Raku
"Hello mate".rindex; # returns 9
"Hello mate".rindex; # returns 1
"word".rindex; # returns Nil


' Examples in Visual Basic
InStrRev ' returns 10
InStrRev ' returns 2
InStrRev ' returns 0

right

FormatLanguages
string Ada
RightVB
RIGHT$BASIC
rightFreeBASIC, Ingres, Pick Basic
strcpy C
string.SubstringC#
stringGo
string.substringJava
string.sliceJavaScript
rightRexx, Erlang
substrPerl 5, PHP
substr
string.substr
Raku
stringCobra, Python
stringPick Basic
Scheme
stringRuby, Ya
stringD
String.sub string nOCaml
string.sub
:sub
Lua
string last: nSmalltalk
StringTakeMathematica
string COBOL
¯nstring.APL


// Examples in Java; extract rightmost 4 characters
String str = "CarDoor";
str.substring; // returns 'Door'


  1. Examples in Raku
"abcde".substr; # returns "cde"
"abcde".substr; # 'out of range' error


/* Examples in Rexx */
right /* returns "cde" */
right /* returns " abcde" */
right /* returns "***abcde" */


; Examples in Scheme
; returns "cde"
; error


' Examples in Visual Basic
Right ' returns "idi"
Right ' returns "sandroguidi"

rpartition

FormatLanguages
string.rpartitionPython, Ruby


  1. Examples in Python
"Spam eggs spam spam and ham".rpartition ###
"Spam eggs spam spam and ham".rpartition ###

slice

see #substring

split

FormatLanguages
splitPerl 5
split
string.split
Raku
explodePHP
string.splitPython
string.splitJavaScript, Java, Ruby
string:tokensErlang
strings.Split
strings.SplitN
Go
Scheme
SplitVB
string.SplitVB.NET, C#, F#
string -split separator«, limit«, options»»Windows PowerShell
Str.split stringOCaml
std.string.splitD
Objective-C
string.componentsSeparatedByStringSwift
TStringList.Delimiter, TStringList.DelimitedTextObject Pascal
StringSplitMathematica
string.split«»Cobra
split string separatorTcl
string or separatorstring in APL2 and Dyalog APL 16.0 respectivelyAPL


// Example in C#
"abc,defgh,ijk".Split; //
"abc,defgh;ijk".Split; //


% Example in Erlang
string:tokens. %


// Examples in Java
"abc,defgh,ijk".split; //
"abc,defgh;ijk".split; //


var
lStrings: TStringList;
lStr: string;
begin
lStrings := TStringList.Create;
lStrings.Delimiter := ',';
lStrings.DelimitedText := 'abc,defgh,ijk';
lStr := lStrings.Strings; // 'abc'
lStr := lStrings.Strings; // 'defgh'
lStr := lStrings.Strings; // 'ijk'
end;


  1. Examples in Perl 5
split; #
split; #


  1. Examples in Raku
'Spam eggs spam spam and ham'.split; #
split; #

sprintf

see #Format

strip

see #trim

strcmp

see #Compare

substring

Definitionsubstring returns string
substr 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. Note that for variable-length encodings such as UTF-8, UTF-16 or Shift-JIS, it can be necessary to remove string positions at the end, in order to avoid invalid strings.


// Examples in C#
"abc".Substring: // returns "b"
"abc".Substring; // returns "bc"
"abc".Substring; // error


;; Examples in Common Lisp
; returns "b"
; returns "c"


% Examples in Erlang
string:substr. % returns "b"
string:substr. % returns "bc"


  1. Examples in Perl 5
substr; # returns "b"
substr; # returns "bc"


  1. Examples in Raku
"abc".substr; # returns "b"
"abc".substr; # returns "bc"


  1. Examples in Python
"abc" # returns "b"
"abc" # returns "bc"


/* Examples in Rexx */
substr /* returns "b" */
substr /* returns "bc" */
substr /* returns "bc " */
substr /* returns "bc****" */

Uppercase

Definitionuppercase returns string
DescriptionReturns the string in upper case.


// Example in C#
"Wiki means fast?".ToUpper; // "WIKI MEANS FAST?"


  1. Example in Perl 5
uc; # "WIKI MEANS FAST?"


  1. Example in Raku
uc; # "WIKI MEANS FAST?"
"Wiki means fast?".uc; # "WIKI MEANS FAST?"


/* Example in Rexx */
translate /* "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
; "WIKI MEANS FAST?"


' Example in Visual Basic
UCase ' "WIKI MEANS FAST?"

trim

trim or strip is used to remove whitespace from the beginning, end, or both beginning and end, of a string.
Example usageLanguages
String.TrimC#, VB.NET, Windows PowerShell
string.strip;D
Clojure
sequence trimFactor
Common Lisp
Scheme
string.trimJava, JavaScript
TrimPascal, QBasic, Visual Basic, Delphi
string.stripPython
strings.TrimGo
LTRIMOracle SQL, T-SQL
stripREXX
string:stripErlang
string.strip or string.lstrip or string.rstripRuby
string.trimRaku
trimPHP, Raku
Cocoa
string withBlanksTrimmed
string withoutSpaces
string withoutSeparators
Smalltalk
Smalltalk
stripSAS
string trim $stringTcl
TRIM or TRIMFortran
TRIMSQL
TRIM or LTrim or RTrimColdFusion
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

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

AWK

In AWK, one can use regular expressions to trim:

ltrim = gsub
rtrim = gsub
trim = ltrim; rtrim

or:

function ltrim
function rtrim
function trim

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:

  1. include
  2. include
void rtrim
void ltrim
void trim

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

  1. include
trimmed = boost::algorithm::trim_copy;

Note that with boost's function named simply trim the input sequence is modified in-place, and does not return a result.
Another open source C++ library Qt has several trim variants, including a standard one:

  1. include
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.

Haskell

A trim algorithm in Haskell:

import Data.Char
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 is optional.

J

The trim algorithm in J is a functional description:

trim =. #~ : ' '&~:

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, and the [ECMAScript 5
standard. In earlier versions it can be added to the String object's prototype as follows:

String.prototype.trim = function ;

Perl

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

or:

$string =~ s/^\s+|\s+$//g ; # remove both leading and trailing whitespace

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 from a string if present..
In Raku, the upcoming sister language of Perl, strings have a trim method.
Example:

$string = $string.trim; # remove leading and trailing whitespace
$string.= trim; # same thing

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.
Example of trimming vowels:

set string onomatopoeia
set trimmed ;# result is nomatop
set r_trimmed ;# result is onomatop
set l_trimmed ;# result is nomatopoeia

XSLT

includes the function normalize-space which strips leading and trailing whitespace, in addition to replacing any whitespace sequence with a single 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.
OWIKI.org. Text is available under the Creative Commons Attribution-ShareAlike License.