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. Note, string concatenation and regular expressions are handled in separate pages. Statements in guillemets (« … ») are optional.
{ Example in Pascal }varMyStr:string='Hello, World';MyChar:Char;beginMyChar:=MyStr[2];// 'e'
# Example in ALGOL 68 #
"Hello, World"[2]; // 'e'
// Example in C# and Ya"Hello, World"[2];// 'l'
# Examples in Python"Hello, World"[2]# 'l'"Hello, World"[-3]# 'r'
' Example in Visual BasicMid("Hello, World",2,1)
' Example in Visual Basic .NET"Hello, World".Chars(2)' "l"c
" Example in Smalltalk "'Hello, World'at:2."$e"
Compare (integer result)
Definition
compare(string1,string2) returns integer.
Description
Compares 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.
Format
Languages
IF string1<string2 THEN -1 ELSE ABS (string1>string2) FI
(stringOP? string1string2), where OP can be any of =, -ci=, <, -ci<, >, -ci>, <=, -ci<=, >= and -ci>= (operators starting with '-ci' are case-insensitive)
(stringOP string1string2), where OP can be any of =, -ci=, <>, -ci<>, <, -ci<, >, -ci>, <=, -ci<=, >= and -ci>= (operators starting with '-ci' are case-insensitive)
(stringOP string1string2), where OP can be any of =, -equal, /=, -not-equal, <, -lessp, >, -greaterp, <=, -not-greaterp, >= and -not-lessp (the verbal operators are case-insensitive)
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)
Concatenates (joins) 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.
{ 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"
Contains
Definition
contains(string,substring) returns boolean
Description
Returns 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.
¢ 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 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".
' Example in Visual Basic"hello"="world"' returns false
# Example in Windows PowerShell
"hello" -eq "world" # returns false
Find
Definition
find(string,substring) returns integer
Description
Returns 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.
Related
instrrev
Format
Languages
If not found
string in string(substring, pos, string[startpos:])
" Examples in Smalltalk "'Hello mate'indexOfSubCollection:'ate'"returns 8"'Hellomate'indexOfSubCollection:'late'"returns 0"I'Hellomate'indexOfSubCollection:'late'ifAbsent:[ 99 ] "returns 99"'Hellomate'indexOfSubCollection:'late'ifAbsent:[ selferror ] "raises an exception"
Find character
Definition
find_character(string,char) returns integer
Description
Returns 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.
returns 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.)
// 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,[10] while VERIFY returns the position of the first character that does not belong to the set.[11]
// 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 JavaString.format("My %s costs $%2f","pen",19.99);// returns "My pen costs $19.99"
# 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 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" */
Inequality
Tests if two strings are not equal. See also #Equality.
Format
Languages
string1nestring2, or string1 NE string2
ALGOL 68 - note: the operator "ne" is literally in bold type-font.
Returns 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).
Returns 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.
// Example in C#"Wiki means fast?".ToLower();// "wiki means fast?"
; Example in Scheme(use-modules(srfisrfi-13))(string-downcase"Wiki means fast?"); "wiki means fast?"
/* Example in C */#include <ctype.h>#include <stdio.h>intmain(void){charstring[]="Wiki means fast?";inti;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?" */return0;}
" Example in Smalltalk "'hello'reversed" returns 'olleh' "
# Example in Perlreverse"hello"# returns "olleh"
# Example in Python"hello"[::-1]# returns "olleh"
; Example in Scheme(use-modules(srfisrfi-13))(string-reverse"hello"); returns "olleh"
rfind
Definition
rfind(string,substring) returns integer
Description
Returns 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.
Returns 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).
; Examples in Scheme(use-modules(srfisrfi-13))(string-take-right"abcde",3); returns "cde" (string-take-right"abcde",8); error
' Examples in Visual BasicRight("sandroguidi",3)' returns "idi" Right("sandroguidi",100)' returns "sandroguidi"
// Examples in Java; extract rightmost 4 charactersStringstr="CarDoor";str.substring(str.length()-4);// returns 'Door'
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.
Description
Splits the given string by the right-most separator and returns the three substrings that together make the original.
<string>.split(separator[, limit]) splits a string on separator, optionally only up to a limited number of substrings
Description
Splits 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. See the example here. The Cobra implementation will default to whitespace. Opposite of join.
Returns 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.
// Example in C#"Wiki means fast?".ToUpper();// "WIKI MEANS FAST?"
/* Example in REXX */translate("Wiki means fast?")/* "WIKI MEANS FAST?" *//* Example #2 */
A='This is an example.'
UPPERA/* "THIS IS AN EXAMPLE." *//* Example #3 */
A='upper using Translate Function.'
TranslateUPPERVARAZ/* Z="UPPER USING TRANSLATE FUNCTION." */
; Example in Scheme(use-modules(srfisrfi-13))(string-upcase"Wiki means fast?"); "WIKI MEANS FAST?"
' Example in Visual BasicUCase("Wiki means fast?")' "WIKI MEANS FAST?"
^ abThe transform function exists in the std:: namespace. You must include the <algorithm> header file to use it. The tolower and toupper functions are in the global namespace, obtained by the <ctype.h> header file. The std::tolower and std::toupper names are overloaded and cannot be passed to std::transform without a cast to resolve a function overloading ambiguity, e.g. std::transform(string.begin(), string.end(), result.begin(), (int (*)(int))std::tolower);
^std::string only, result is stored in string result which is at least as long as string, and may or may not be string itself
^ abonly ASCII characters as Ruby lacks Unicode support
^ abcdeThe "find" string in this construct is interpreted as a regular expression. Certain characters have special meaning in regular expressions. If you want to find a string literally, you need to quote the special characters.