Ilmu Informatika    
   
Daftar Isi
(Sebelumnya) Comparison of programming lang ...Comparison of programming lang ... (Berikutnya)

Perbandingan -- programming languages (string functions)

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.

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.

Contents

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(string,integer) returns character.
DescriptionReturns character at index in the string.
EquivalentSee substring of length 1 character.
FormatLanguagesBase index
string[i]ALGOL 68, Pascal, Object Pascal (Delphi), Seed71
string[i]C, C++, C#, D, FreeBASIC, Go, Python1, PHP, Ruby1, Windows PowerShell, JavaScript0
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.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)Perl10
substr(string, i, 1)PL/I1
string.at(i)C++ (std::string only) (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)
Lua11
string at: iSmalltalk (w/ bounds checking)1
string index string iTcl0
StringTake[string, {i}]Mathematica11
string@iEiffel1
  1. In this language, the index can be negative, which then indicates the number of places before the end of the 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#"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)

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

IF string1<string2 THEN -1 ELSE ABS (string1>string2) FI

ALGOL 68
cmp(string1, string2)Python (before 3.0 only)
(string1 > string2) - (string1 < string2)Python (since 3.0)
strcmp(string1, string2)C, C++ (char * only), PHP
std.string.cmp(string1, string2)D
StrComp(string1, string2)VB, Object Pascal (Delphi)
string1 cmp string2Perl
string1 <=> string2Ruby
string1.compare(string2)C++ (std::string only)
compare(string1, string2)REXX, Seed7
CompareStr(string1, string2)Pascal, Object Pascal (Delphi)
string1.compareTo(string2)Java
string1.CompareTo(string2)VB .NET, C#, F#
(= 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 (returns LESS, EQUAL, or GREATER)
compare string1 string2Haskell (returns LT, EQ, or GT)
[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 (returns .TRUE. or .FALSE.). These functions are based on the ASCII collating sequence.
string1.localeCompare(string2)JavaScript
bytes.Compare([]byte(string1), []byte(string2))Go
string compare ?-nocase? ?-length int? string1 string2Tcl
compare(string1,string2,count)PL/I1

1IBM extension.

# Example in Pythoncmp("hello", "world")  # returns -1
/** 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)

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
(stringX? string1 string2), where X can be any of =, -ci=, <, -ci<, >, -ci>, <=, -ci<=, >= and -ci>= (operators starting with '-ci' are case-insensitive)Scheme
(stringX string1 string2), where X can be any of =, -ci=, <>, -ci<>, <, -ci<, >, -ci>, <=, -ci<=, >= and -ci>= (operators starting with '-ci' are case-insensitive)Scheme (SRFI 13)
(stringX string1 string2), where X can be any of =, -equal, /=, -not-equal, <, -lessp, >, -greaterp, <=, -not-greaterp, >= and -not-lessp (the verbal operators are case-insensitive)Common Lisp
(stringX string1 string2), where X 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
string1 op string2, where op can be any of ==, !=, <, >, <= and >=C++ (std::string only), C#, D, Go, JavaScript, Python, PHP, Ruby
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. The operators use the compiler's default collating sequence.
% Example in Erlang"hello" > "world". % returns false
# Example in Windows PowerShell"hello" -gt "world"   # returns false
; Example in common lisp(string> "art" "painting")  ; returns nil(string< "art" "painting")  ; returns non nil

Concatenation

Definitionconcatenate(string1,string2) returns string.
DescriptionConcatenates (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.
FormatLanguages
string1 & string2Ada, FreeBASIC, Seed7, BASIC, VB, VB .NET
strcat(string1, string2)C, C++ (char * only; modifies string1, which must have enough space to store the result)
string1 . string2Perl, PHP
string1 + string2ALGOL 68, C++ (std::string only), C#, FreeBASIC, Go, Pascal, Object Pascal (Delphi), Java, JavaScript, Windows PowerShell, Python, Ruby, F#, Turing, VB
string1 ~ string2D
(string-append string1 string2)Scheme
(concatenate 'string string1 string2)Common Lisp
(string-append string1 string2)ISLISP
(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
string1 string2SNOBOL
string1 <> string2Mathematica
{ 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

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.
Related
FormatLanguages
string_in_string(string, loc int, substring)ALGOL 68
ContainsStr(string, substring)Object Pascal (Delphi)
string.Contains(substring)C#, VB .NET, Windows PowerShell, F#
string.contains(substring)Java (1.5+)
string.indexOf(substring) >= 0JavaScript
strpos(string, substring) !== falsePHP
substring in stringPython (2.3+)
string.find(string, substring) ~= nilLua
string.include?(substring)Ruby
Data.List.isInfixOf substring stringHaskell (GHC 6.6+)
string includesSubString: substringSmalltalk (Squeak, Pharo)
String.isSubstring substring stringStandard ML
(search substring string)Common Lisp
?ISLISP
(substring? substring string)Clojure
! StringFreeQ[string, substring]Mathematica
index(string, substring, startpos)>0PL/I1

1startpos is IBM extension.

¢ 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

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++(std::string only), C# Go, JavaScript (similarity), PHP (similarity), Ruby, Erlang, Haskell, Lua, D, Mathematica
string1 === string2JavaScript, PHP
string1 == string2 or
string1 .EQ. string2
Fortran
strcmp(string1, string2) == 0C, C++ (char * only)
(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
test string1 = string2, or
[ string1 = string2 ]
Bourne Shell
string1 eq string2Perl
string1.equals(string2)Java
string1 -eq string2, or
[string]::Equals(string1, string2)
Windows PowerShell
[string1 isEqualToString:string2], or
[string1 isEqual:string2]
Objective-C (NSString * only)
// Example in C#"hello" == "world"   // returns false
' Example in Visual Basic"hello" = "world" '  returns false
# Example in Windows PowerShell"hello" -eq "world"  #  returns false

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(«startposstring,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»)Perlreturns -1
instr(«startposstring,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.find(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++ (std::string only)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 Just 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: startpos
Smalltalk (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/I1returns 0 (positions start at 1)

1startpos is IBM extension.

; Examples in Common Lisp(search "e" "Hello mate") ;  returns 1(search "z" "word")   ;  returns NIL
// Examples in C#"Hello mate".IndexOf("e"); // returns 1"Hello mate".IndexOf("e", 4); // returns 9"word".IndexOf("z");  // returns -1
; Examples in Scheme(use-modules (srfi srfi-13))(string-contains "Hello mate" "e") ;  returns 1(string-contains "word" "z")  ;  returns #f
' Examples in Visual BasicInStr("Hello mate", "e")  '  returns 2InStr(5, "Hello mate", "e")   '  returns 10InStr("word", "z") '  returns 0
" Examples in 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++ (std::string only)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») or
position = VERIFY (string, set «, back» «, kind»)[a]
Fortranreturns zero
string indexOf: char ifAbsent: aBlock
string indexOf: char
string includes: char
Smalltalkevaluate aBlock which is a BlockClosure (or any object understanding value)
returns 0
returns true or false
index(string, char, startpos )PL/I1returns 0 (positions start at 1)

1startpos is IBM extension.

// 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,[1] while VERIFY returns the position of the first character that does not belong to the set.[2]

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, RubyC
io_lib:format(formatstring, items)Erlang 
sprintf(outputstring, formatstring, items)C, C++ (char * only)C
std.string.format(formatstring, items)DC
Format(formatstring, items)Object Pascal (Delphi) 
fmt.Sprintf(formatstring, items)GoC
printf -v outputstring formatstring itemsBash shellC
formatstring % (items)Python, RubyC
formatstring.format(items)Python 3.x.NET
Printf.sprintf formatstring itemsOCaml, F# (formatstring must be a fixed literal at compile time for it to have the correct type)C
Text.Printf.printf formatstring itemsHaskell (GHC)C
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)
(formatstring):format(items)
LuaC
WRITE (outputstring, formatstring) itemsFortranFortran
put string(string) edit(items)(format)PL/IPL/I (similar to Fortran)
// 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.

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 (Delphi), OCaml, PHP, Seed7, Standard ML, F#
string1 # string2BASIC (some implementations)
string1 ne string2Perl
(string<> string1 string2)Scheme (SRFI 13)
(string/= string1 string2)Common Lisp
(string/= string1 string2)ISLISP
(not= string1 string2)Clojure
string1 != string2C++ (std::string only), C#, Go, JavaScript (not similar), PHP (not similar), Python, Ruby, D, Mathematica
string1 !== string2JavaScript, PHP
string1 \= string2REXX
string1 ¬= string2PL/I
test string1 != string2, or
[ string1 != string2 ]
Bourne Shell
string1 -ne string2, or
-not [string]::Equals(string1, string2)
Windows PowerShell
string1 ~= string2Lua, Smalltalk
// Example in C#"hello" != "world" // returns true
' Example in Visual Basic"hello" <> "world" '  returns true
; Example in Clojure(not= "hello" "world")  ; ⇒ true
# Example in Windows PowerShell"hello" -ne "world"   #  returns true

index

see #Find

indexof

see #Find

instr

see #Find

instrrev

see #rfind

join

Definitionjoin(separator, list_of_strings) joins a list of strings 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
implode(separator, array_of_strings)PHP
separator.join(sequence_of_strings)Python
array_of_strings.join(separator)Ruby, JavaScript
(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#
&{$OFS=$separator; "$array_of_strings"}, or
array_of_strings -join separator
Windows 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 ]Smalltalk (Squeak, Pharo)
// Example in C#String.Join("-", {"a", "b", "c"})  // "a-b-c"
# Example in Perljoin( '-', ('a', 'b', 'c'));   # '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"

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).
FormatLanguages
string (string'First .. string'First + n - 1)Ada
string:substr(string, start, length)Erlang
Left(string,n)VB
LEFT$(string,n)BASIC
left(string,n)FreeBASIC, Ingres
left(string,n «,padchar»)REXX, Erlang
substr(string, 0, n)AWK (changes string), Perl, PHP
string[:n]Python
string[0, n]
string[0..n - 1]
Ruby
string.substr(0,n)C++ (std::string only)
string[0 .. n]D (if n is larger than the length of the string, then in Debug mode ArrayRangeException is thrown, in Release mode, the behaviour is unspecified)
string[ .. n]Seed7
string.Substring(0,n)VB .NET, C#, Windows PowerShell, F#
leftstr(string, n)Pascal, Object Pascal (Delphi)
string.substring(0,n)Java, JavaScript (if n is larger than the length of the string, Java will throw an IndexOutOfBoundsException)
(string-take string n)Scheme (SRFI 13)
take n stringHaskell
(apply str (take n string))Clojure
[string substringToIndex:n]Objective-C (NSString * only)
String.extract (string, n, NONE)Standard ML
String.sub string 0 nOCaml (if n is larger than length of string, raises Invalid_argument)
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 (if n is larger than length of string, throw the message "StringTake::take:")
/* 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 BasicLeft("sandroguidi", 3)   '  returns "san" Left("sandroguidi", 100) '  returns "sandroguidi"

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'Length Ada
UPB string ALGOL 68
length(string) Ingres, Perl, Pascal, Object Pascal (Delphi), REXX, Seed7, SQL, PL/I
len(string) BASIC, FreeBASIC, Python, Go
length(string), string:len(string) Erlang
Len(string) VB
string.LengthNumber of 16-bit UTF-16-encoded blocksVB .NET, C#, Windows PowerShell, F#
string.size OR string.lengthNumber of bytes (Ruby lacks Unicode support)Ruby
strlen(string)Number of bytesC, C++ (char * only), PHP
string.length() C++ (std::string only)
string.length D
string.length()Number of 16-bit UTF-16-encoded blocksJava
string.length JavaScript
(string-length string) Scheme
(length string) Common Lisp
(length string) ISLISP
(count string) Clojure
String.length string OCaml
size string Standard ML
length stringNumber of Unicode codepointsHaskell
[string length] Objective-C (NSString * only)
string.len(string)
(string):len()
#string
 Lua
string size Smalltalk
LEN(string), or LEN_TRIM(string) Fortran
StringLength[string] Mathematica
// Examples in C#"hello".Length;  // returns 5"".Length;   // returns 0
# Examples in Erlangstring:len("hello"). %  returns 5string:len("").  %  returns 0
# Examples in Perllength("hello"); #  returns 5length("");  #  returns 0
' Examples in Visual BasicLen("hello") '  returns 5Len("")  '  returns 0
//Examples in Objective-C[@"hello" Length]   //returns 5[@"" Length]   //returns 0
-- Examples in Lua("hello"):len() -- returns 5#"" -- returns 0

locate

see #Find


Lowercase

Definitionlowercase(string) returns string
DescriptionReturns the string in lower case.
FormatLanguages
LCase(string)VB
lcase(string)FreeBASIC
lc(string)Perl
tolower(char)C (operates on one character)
std.string.toLower(string)D
transform(string.begin(), string.end(), result.begin(), ::tolower)[3]C++ (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)
lowercase(string)Object Pascal (Delphi)
strtolower(string)PHP
echo "string" | tr 'A-Z' 'a-z'Unix
string.lower()Python
string.downcaseRuby (only ASCII characters as Ruby lacks Unicode support)
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 lowercaseString]Objective-C (NSString * only)
string.lower(string)
(string):lower()
Lua
string asLowercaseSmalltalk
LOWER(string)SQL
lowercase(string)PL/I1
ToLowerCase[string]Mathematica

1IBM extension.

// 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;}

mid

see #substring1


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.
FormatLanguages
string.partition(separator)Python, Ruby(1.9+)
lists:partition(pred, string)Erlang
split /(separator)/, string, 2Perl
# 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 Perlsplit /(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

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
string.Replace(find, replace)VB .NET, C#, F#
str_replace(find, replace, string)PHP
re:replace(string, find, replace, «{return, list}»)Erlang
string.replace(find, replace)Python, Java (1.5+)
string.replaceAll(find_regex, replace)[4]Java
string.gsub(find, replace)Ruby
string =~ s/find_regex/replace/g[4]Perl
string.replace(find, replace, "g") (third parameter is non-standard) or
string.replace(/find_regex/g, replace)[4]
JavaScript
echo "string" | sed 's/find_regex/replace/g'[4]Unix
string.replace(find, replace), or
string -replace find_regex, replace[4]
Windows PowerShell
Str.global_replace (Str.regexp_string find) replace stringOCaml
[string stringByReplacingOccurrencesOfString:find withString:replace]Objective-C (NSString * only)
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
// 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 Visual BasicReplace("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

Definitionreverse(string)
DescriptionReverses the order of the characters in the string.
FormatLanguages
reverse stringPerl, Haskell
lists:reverse(string)Erlang
strrev(string)PHP
string[::-1]Python
(string-reverse string)Scheme (SRFI 13)
(reverse string)Common Lisp
string.reverseRuby
new StringBuilder(string).reverse().toString()Java
std::reverse(string.begin(), string.end());C++ (std::string only, modifies string)
StrReverse(string)VB
string.Reverse().ToString()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
# Example in Perlreverse "hello"  # returns "olleh"
# Example in Python"hello"[::-1] # returns "olleh"
; Example in Scheme(use-modules (srfi srfi-13))(string-reverse "hello") ; returns "olleh"

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(«startposstring,substring)VBreturns 0
instrrev(«startposstring,substring)FreeBASICreturns 0
rindex(string,substring«,startpos»)Perlreturns -1
strrpos(string,substring«,startpos»)PHPreturns FALSE
string.rfind(substring«,startpos»)C++ (std::string only)returns std::string::npos
std.string.rfind(string, substring)Dreturns -1
string.rfind(substring«,startpos«, endpos»»)Pythonreturns -1
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
; 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 Visual BasicInStrRev("Hello mate", "e")  '  returns 10InStrRev(5, "Hello mate", "e")   '  returns 2InStrRev("word", "z") '  returns 0


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
string.substring(string.length()-n)Java
string.slice(-n)JavaScript[5]
right(string,n «,padchar»)REXX, Erlang
substr(string,-n)Perl, PHP
string[-n:]Python
(string-take-right string n)Scheme (SRFI 13)
string[-n..-1]Ruby
string[$-n .. $]D (if n is larger than length of string, then in Debug mode ArrayRangeException is thrown, and unspecified behaviour in Release mode)
String.sub string (String.length string - n) nOCaml (if n is larger than length of string, raises Invalid_argument)
string.sub(string, -n)
(string):sub(-n)
Lua
string last: nSmalltalk (Squeak, Pharo)
StringTake[string, -n]Mathematica (if n is larger than length of string, throw the message "StringTake::take:")
/* 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 BasicRight("sandroguidi", 3) '  returns "idi" Right("sandroguidi", 100)  '  returns "sandroguidi"
// Examples in Java; extract rightmost 4 charactersString str = "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.
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
# 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')

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. See the example here. Opposite of join.
FormatLanguages
split(/separator/, string«, limit»)Perl
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)
TStringList.Delimiter, TStringList.DelimitedTextObject Pascal
StringSplit[string, separator«, limit»]Mathematica
// Example in C#"abc,defgh,ijk".Split(','); // {"abc", "defgh", "ijk"}"abc,defgh;ijk".Split(',', ';'); // {"abc", "defgh", "ijk"}
% Example in Erlangstring: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 Pascalvar  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 Perlsplit(/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')

sprintf

see #Format

strip

see #trim


strcmp

see #Compare (integer result)


substring1

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.
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
MID$(string, startpos, numChars)BASIC
substr(string, startpos, numChars)AWK (changes string), Perl2,4, PHP2,4
substr(string, startpos «,numChars, padChar»)REXX
string[startpos:endpos]Python2,3, Go
string[startpos, numChars]
string[startpos .. endpos-1]
string[startpos ... endpos]
Ruby2,3
string[startpos .. endpos]
string[startpos len numChars]
Seed7
string.slice(startpos«, endpos»)JavaScript2,3
string.substr(startpos«, numChars»)C++ (std::string only), 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
char result[numChars+1] = "";
strncat(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)
Lua2,3
string copyFrom: startpos to: endposSmalltalk
string(startpos:endpos)Fortran
SUBSTRING(string FROM startpos «FOR numChars»)SQL
StringTake[string, {startpos, endpos}]Mathematica2,3
  1. See CharAt for base of startpos/endpos.
  2. In this language, startpos can be negative, which indicates to start that number of places before the end of the string.
  3. In this language, endpos can be negative, which indicates to end that number of places before the end of the string.
  4. In this language, numChars can be negative, which indicates to end that number of places before the end of the string.
// 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 "bc" <source lang="text">% Examples in Erlangstring:substr("abc", 2, 1). %  returns "b"string:substr("abc", 2). %  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

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
toupper(char)C (operates on one character)
std.string.toUpper(string)D
transform(string.begin(), string.end(), result.begin(), toupper)[3]C++ (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)
uppercase(string)Object Pascal (Delphi)
upcase(char)Object Pascal (Delphi) (operates on one character)
strtoupper(string)PHP
echo "string" | tr 'a-z' 'A-Z'Unix
translate(string), or

UPPER variables, or
PARSE UPPER VAR SrcVar DstVar

REXX
string.upper()Python
string.upcaseRuby (only ASCII characters as Ruby lacks Unicode support)
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
to_upper(string)Erlang
string.ToUpper()VB .NET, C#, Windows PowerShell, F#
[string uppercaseString]Objective-C (NSString * only)
string.upper(string)
(string):upper()
Lua
string asUppercaseSmalltalk
UPPER(string)SQL
ToUpperCase[string]Mathematica
// 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.'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 BasicUCase("Wiki means fast?")  '  "WIKI MEANS FAST?"

trim

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

FormatLanguages
StringTrim[string]Mathematica
(string-trim '(#\Space #\Tab #\Newline) string)Common Lisp
string.trim()Java
string.trim()

string.replace(^\s+|\s+$/g, "")

JavaScript
trim(string)PHP

Notes

  1. ^ http://fortranwiki.org/fortran/show/s can
  2. ^ http://fortranwiki.org/fortran/show/v erify
  3. ^ a b The 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);
  4. ^ a b c d e The "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.
  5. ^ http://es5.github.com/#x15.5.4.13

External links

(Sebelumnya) Comparison of programming lang ...Comparison of programming lang ... (Berikutnya)