Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Comparison of programming languages (string functions)

From Wikipedia, the free encyclopedia
(Redirected fromString manipulation algorithm)

"String functions" redirects here. For string functions in formal language theory, seeString operations.
Further information:Comparison of programming languages
Comparison of
programming languages

Stringfunctions are used in computerprogramming languages to manipulate astring or query information about a string (some do both).

Most programming languages that have a stringdatatype 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, likeC# andJava have immutable strings and return a copy (in newly allocated dynamic memory), while others, likeC manipulate the original string unless the programmer copies data to a new string. See for exampleConcatenation below.

The most basic example of a string function is thelength(string) function. This function returns the length of astring 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 aslen(string). The below list of common functions aims to help limit this confusion.

Common string functions (multi language reference)

[edit]
icon
This sectiondoes notcite anysources. Please helpimprove this section byadding citations to reliable sources. Unsourced material may be challenged andremoved.(July 2013) (Learn how and when to remove this message)

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, stringconcatenation andregular expressions are handled in separate pages. Statements inguillemets (« … ») are optional.[citation needed]

CharAt

[edit]
DefinitioncharAt(string,integer) returns character.
DescriptionReturns character at index in the string.
EquivalentSeesubstring 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,[1]PHP,Ruby,[1]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)Rust[2]0
string[i,1]Pick Basic1
String.sub (string,i)Standard ML0
string !!iHaskell0
(string-refstringi)Scheme0
(charstringi)Common Lisp0
(eltstringi)ISLISP0
(getstringi)Clojure0
substr(string,i, 1)Perl 5[1]0
substr(string,i, 1)
string.substr(i, 1)
Raku[3]0
substr(string,i, 1)PL/I1
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)
Lua[1]1
string at:iSmalltalk (w/ bounds checking)1
string indexstring iTcl0
StringTake[string, {i}]Mathematica,Wolfram Language[1]1
string@iEiffel1
string (i:1)COBOL1
${string_param:i:1}Bash0
istringAPL0 or 1
{ Example in Pascal }varMyStr:string='Hello, World';MyChar:Char;beginMyChar:=MyStr[2];// 'e'
# Example in ALGOL 68 #"Hello, World"[2];             // 'e'
// Example in C#include<stdio.h>charmyStr1[]="Hello, World";printf("%c",*(myStr1+1));// 'e'printf("%c",*(myStr1+7));// 'W'printf("%c",myStr1[11]);// 'd'printf("%s",myStr1);// 'Hello, World'printf("%s","Hello(2), World(2)");// 'Hello(2), World(2)'
importstd;usingstd::string;charmyStr1[]="Hello(1), World(1)";stringmyStr2="Hello(2), World(2)";std::println("Hello(3), World(3)");// 'Hello(3), World(3)'std::println("{}",myStr2[6]);// '2'std::println("{}",myStr1.substr(5,3));// '(1)'
// Example in C#"Hello, World"[2];// 'l'
# Example in Perl 5substr("Hello, World",1,1);# 'e'
# Examples in Python"Hello, World"[2]#  'l'"Hello, World"[-3]#  'r'
# Example in Raku"Hello, World".substr(1,1);# 'e'
' Example in Visual BasicMid("Hello, World",2,1)
' Example in Visual Basic .NET"Hello, World".Chars(2)'  "l"c
" Example in Smalltalk "'Hello, World'at:2."$e"
//Example in Rust"Hello, World".chars().nth(2);// Some('l')

Compare (integer result)

[edit]
See also:Three-way comparison
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 islexicographically 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
IFstring1<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 cmpstring2Perl,Raku
string1 compare:string2Smalltalk (Squeak,Pharo)
string1 <=>string2Ruby,C++ (STL,C++20)[4]
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#
(comparestring1string2)Clojure
(string=string1string2)Common Lisp
(string-comparestring1string2p<p=p>)Scheme (SRFI 13)
(string=string1string2)ISLISP
comparestring1string2OCaml
String.compare (string1,string2)Standard ML[5]
comparestring1string2Haskell[6]
[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[7]
string1.localeCompare(string2)JavaScript
bytes.Compare([]byte(string1),[]byte(string2))Go
string comparestring1string2Tcl
compare(string1,string2,count)PL/I[8]
string1.cmp(string2)Rust[9]
# Example in Perl 5"hello"cmp"world";# returns -1
# Example in Pythoncmp("hello","world")# returns -1
# Examples in Raku"hello"cmp"world";# returns Less"world"cmp"hello";# returns More"hello"cmp"hello";# returns Same
/** Example in Rexx */compare("hello","world")/* returns index of mismatch: 1 */
; Example in Scheme(use-modules(srfisrfi-13)); returns index of mismatch: 0(string-compare"hello""world"valuesvaluesvalues)

Compare (relational operator-based, Boolean result)

[edit]
Definitionstring1 OP string2 OR(compare string1 string2) returns Boolean.
DescriptionLexicographically compares two strings using a relational operator or function. Boolean result returned.
FormatLanguages
string1 OPstring2, whereOP can be any of=, <>, <, >, <= and>=Pascal,Object Pascal (Delphi),OCaml,Seed7,Standard ML,BASIC,VB,VB .NET,F#
string1 OPstring2, whereOP can be any of=, /=, ≠, <, >, <=, ≤ and; Also:EQ, NE, LT, LE, GE andGTALGOL 68
(stringOP?string1string2), whereOP can be any of=, -ci=, <, -ci<, >, -ci>, <=, -ci<=, >= and-ci>= (operators starting with '-ci' are case-insensitive)Scheme
(stringOPstring1string2), whereOP can be any of=, -ci=, <>, -ci<>, <, -ci<, >, -ci>, <=, -ci<=, >= and-ci>= (operators starting with '-ci' are case-insensitive)Scheme (SRFI 13)
(stringOPstring1string2), whereOP can be any of=, -equal, /=, -not-equal, <, -lessp, >, -greaterp, <=, -not-greaterp, >= and-not-lessp (the verbal operators are case-insensitive)Common Lisp
(stringOPstring1string2), whereOP can be any of=, /=, <, >, <=, and>=ISLISP
string1 OPstring2, whereOP can be any of=, \=, <, >, <= and>=[10]Rexx
string1 OPstring2, whereOP can be any of=, ¬=, <, >, <=, >=, ¬< and¬>[11]PL/I
string1 OPstring2, whereOP can be any of=, /=, <, >, <= and>=Ada
string1 OPstring2, whereOP can be any of==, /=, <, >, =< and>=Erlang
string1 OPstring2, whereOP can be any of==, /=, <, >, <= and>=Haskell
string1 OPstring2, whereOP can be any ofeq,ne,lt,gt,le andgePerl,Raku
string1 OPstring2, whereOP can be any of==, !=, <, >, <= and>=C++ (STL),C#,D,Go,JavaScript,Python,PHP,Ruby,Rust,[12]Swift
string1 OPstring2, whereOP 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 OPstring2, whereOP can be any of==, ~=, <, >, <= and>=Lua
string1 OPstring2, whereOP can be any of=, ~=, <, >, <= and>=Smalltalk
string1 OPstring2, whereOP can be any of==, /=, <, >, <= and>=; Also: .EQ., .NE., .LT., .LE., .GT. and.GE.Fortran.[13]
string1 OPstring2 whereOP can be any of=, <>, <, >, <=, >= as well as worded equivalentsCOBOL
string1 OPstring2 whereOP can be any of==, <>, <, >, <= and>=Cobra
string1 OPstring2 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) whereMETHOD is any ofeq,ne,gt,lt,ge,leRust[12]
% Example in Erlang"hello">"world".% returns false
# Example in Raku"art"gt"painting";# returns False"art"lt"painting";# returns True
# Example in Windows PowerShell"hello"-gt"world"# returns false
;; Example in Common Lisp(string>"art""painting"); returns nil(string<"art""painting"); returns non nil

Concatenation

[edit]
See also: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
string1adjacent_tostring2Rexx (abutment, equivalent tostring1 ||string2)
string1whitespacestring2Rexx (equivalent tostring1 || ' ' ||string2)
string1 &string2Ada,FreeBASIC,Seed7,BASIC,VB,VB .NET,COBOL (between literals only)
strcat(string1,string2)C,C++ (char* only)[14]
string1 .string2Perl,PHP
string1 +string2ALGOL 68,C++ (STL),C#,Cobra,FreeBASIC,Go,Pascal,Object Pascal (Delphi),Java,JavaScript,Windows PowerShell,Python,Ruby,Rust,[15]F#,Swift,Turing,VB
string1 ~string2D,Raku
(string-appendstring1string2)Scheme,ISLISP
(concatenate 'stringstring1string2)Common Lisp
(strstring1string2)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
string1string2SNOBOL
string1string2Bash
string1 <>string2Mathematica
concatstring1 string2Tcl
{ Example in Pascal }'abc'+'def';// returns "abcdef"
// Example in C#"abc"+"def";// returns "abcdef"
' Example in Visual Basic"abc"&"def"'  returns "abcdef""abc"+"def"'  returns "abcdef""abc"&Null'  returns "abc""abc"+Null'  returns Null
// Example in D"abc"~"def";// returns "abcdef"
;; Example in common lisp(concatenate'string"abc ""def ""ghi"); returns "abc def ghi"
# Example in Perl 5"abc"."def";# returns "abcdef""Perl ".5;# returns "Perl 5"
/* Example in PL/I */"abc"||"def"/* returns "abcdef" */
# Example in Raku"abc" ~"def";# returns "abcdef""Perl " ~6;# returns "Perl 6"
/* Example in Rexx */"Strike"2/* returns "Strike2" */"Strike"2/* returns "Strike 2" */

Contains

[edit]
Definitioncontains(string,substring) returns boolean
DescriptionReturns whetherstring containssubstring as a substring. This is equivalent to usingFind 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,[16]C++ (C++23)[17]
string.indexOf(substring) >= 0JavaScript
strpos(string,substring) !== falsePHP
str_contains(string,substring)PHP (8+)
pos(string,substring) <> 0Seed7
substring instringCobra,Python (2.3+)
string.find(string,substring) ~= nilLua
string.include?(substring)Ruby
Data.List.isInfixOfsubstringstringHaskell (GHC 6.6+)
string includesSubstring:substringSmalltalk (Squeak,Pharo,Smalltalk/X)
String.isSubstringsubstringstringStandard ML
(searchsubstringstring)Common Lisp
(not(null(string-indexsubstringstring)))ISLISP
(substring?substringstring)Clojure
! StringFreeQ[string,substring]Mathematica
index(string,substring,startpos)>0Fortran, PL/I[18]
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)
∨/substringstringAPL
¢ Example inALGOL 68 ¢string in string("e",loc int, "Hello mate");      ¢ returnstrue ¢string in string("z",loc int, "word");            ¢ returnsfalse ¢
// Example In C#"Hello mate".Contains("e");// returns true"word".Contains("z");// returns false
#  Example in Python"e"in"Hello mate"#  returns true"z"in"word"#  returns false
#  Example in Raku"Good morning!".contains('z')#  returns False"¡Buenos días!".contains('í');#  returns True
"  Example in Smalltalk "'Hello mate'includesSubstring:'e'" returns true "'word'includesSubstring:'z'" returns false "

Equality

[edit]

Tests if two strings are equal. See also#Compare and#Compare. Note that doing equality checks via a genericCompare 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,[12]Erlang,Haskell,Lua,D,Mathematica,Swift
string1 ===string2JavaScript,PHP
string1 ==string2
string1 .EQ.string2
Fortran
strcmp(string1,string2) == 0C
(string=?string1string2)Scheme
(string=string1string2)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
teststring1 =string2
[string1 =string2 ]
Bourne Shell
string1 eqstring2Perl,Raku,Tcl
string1.equals(string2)Cobra,Java
string1.Equals(string2)C#
string1 -eqstring2
[string]::Equals(string1,string2)
Windows PowerShell
[string1 isEqualToString:string2]
[string1 isEqual:string2]
Objective-C (NSString * only)
string1string2APL
string1.eq(string2)Rust[12]
// Example in C#"hello"=="world"// returns false
' Example in Visual Basic"hello"="world"'  returns false
# Examples in Perl 5'hello'eq'world'# returns 0'hello'eq'hello'# returns 1
# Examples in Raku'hello'eq'world'# returns False'hello'eq'hello'# returns True
# Example in Windows PowerShell"hello"-eq"world"#  returns false
⍝ Example in APL'hello''world'⍝  returns 0


Find

[edit]
Definitionfind(string,substring) returns integer
DescriptionReturns the position of the start of the first occurrence ofsubstring instring. If thesubstring 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»)Perl 5returns −1
index(string,substring«,startpos»)
string.index(substring,«,startpos»)
Rakureturns Nil
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.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-containsstringsubstring)Scheme (SRFI 13)returns #f
(searchsubstringstring)Common Lispreturns NIL
(string-indexsubstringstring)ISLISPreturnsnil
List.findIndex (List.isPrefixOfsubstring) (List.tailsstring)Haskell (returns onlyindex)returns Nothing
Str.search_forward (Str.regexp_stringsubstring)string 0OCamlraises Not_found
Substring.size (#1 (Substring.positionsubstring (Substring.fullstring)))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 INstring)SQLreturns 0 (positions start at 1)
index(string,substring,startpos )PL/I[18]returns 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 firstsubstring string startposTclreturns −1
(substringstring)⍳1APLreturns 1 + the last position instring
string.find(substring)Rust[19]returnsNone

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 inInStr("Hello mate","e")'  returns 2InStr(5,"Hello mate","e")'  returns 10InStr("word","z")'  returns 0
  • Smalltalk
    'Hello mate'indexOfSubCollection:'ate'"returns 8"
    'Hello mate'indexOfSubCollection:'late'"returns 0"
    I'Hellomate'indexOfSubCollection:'late'ifAbsent:[99 ]"returns 99"
    'Hello mate'indexOfSubCollection:'late'ifAbsent:[selferror ]"raises an exception"


Find character

[edit]
Definitionfind_character(string,char) returns integer
DescriptionReturns the position of the start of the first occurrence of the characterchar instring. 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 68returnsBOOL:TRUE orFALSE, and position inREF INT pos.
instr(string, anychar«,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)returnsNULL
std.string.find(string,dchar)Dreturns −1
string.find(char«,startpos»)C++ (STL)returnsstd::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
(positioncharstring)Common LispreturnsNIL
(char-indexcharstring)ISLISPreturnsnil
List.elemIndexcharstringHaskell (returnsJustindex)returnsNothing
String.indexstringcharOCamlraisesNot_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:char
SmalltalkevaluateaBlock which is aBlockClosure (or any object understanding value)
returns 0
returnstrue orfalse
index(string,char,startpos )PL/I[20]returns 0 (positions start at 1)
string.index(?char)Rubyreturnsnil
strpos(string,char,startpos)PHPreturnsfalse
string.indexOf(char«,startpos«,charcount»»)Cobrareturns −1
stringcharAPLreturns 1 + the last position instring
string.find(substring)Rust[19]returnsNone
// 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,[21] while VERIFY returns the position of the first character that does not belong to the set.[22]

Format

[edit]
See also:printf format string
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
printfformatstringitemsUnixC
formatstring % (items)Python,RubyC
formatstring.format(items)Python.NET
fformatstringPython 3
Printf.sprintfformatstring[23]itemsOCaml,F#C
Text.Printf.printfformatstringitemsHaskell (GHC)C
formatstring printf:itemsSmalltalkC
String.format(formatstring,items)JavaC
String.Format(formatstring,items)VB .NET,C#,F#.NET
(formatformatstringitems)Scheme (SRFI 28)Lisp
(format nilformatstringitems)Common LispLisp
(formatformatstringitems)ClojureLisp
formatstring -fitemsWindows 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
formatformatstring itemsTclC
formatnumbersitems
formatstring ⎕FMTitems
APLAPL
format!(formatstring,items)Rust[24]Python
// 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"
# Examples in Rakusprintf"My %s costs \$%.2f","pen",19.99;# returns "My pen costs $19.99"1.fmt("%04d");# returns "0001"
# Example in Python"My%s costs $%.2f"%("pen",19.99);#  returns "My pen costs $19.99""My{0} costs ${1:.2f}".format("pen",19.99);#  returns "My pen costs $19.99"
#Example in Python 3.6+pen="pen"f"My{pen} costs{19.99}"#returns "My pen costs 19.99"
; Example in Scheme(format"My ~a costs $~1,2F""pen"19.99);  returns "My pen costs $19.99"
/* example in PL/I */putstring(some_string)edit('My ','pen',' costs',19.99)(a,a,a,p'$$$V.99')/* returns "My pen costs $19.99" */

Inequality

[edit]

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

FormatLanguages
string1nestring2
string1 NEstring2
ALGOL 68 – note: the operator "ne" is literally inbold 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 nestring2Perl,Raku
(string<>string1string2)Scheme (SRFI 13)
(string/=string1string2)Common Lisp
(string/=string1string2)ISLISP
(not=string1string2)Clojure
string1 !=string2C++ (STL),C#,Go,JavaScript (not similar),PHP (not similar),Python,Ruby,Rust,[12]Swift,D,Mathematica
string1 !==string2JavaScript,PHP
string1 \=string2Rexx
string1 ¬=string2PL/I
teststring1 !=string2
[string1 !=string2 ]
Bourne Shell
string1 -nestring2
-not[string]::Equals(string1,string2)
Windows PowerShell
string1 ~=string2Lua,Smalltalk
string1string2APL
string1.ne(string2)Rust[12]
// Example in C#"hello"!="world"// returns true
' Example in Visual Basic"hello"<>"world"'  returns true
;; Example in Clojure(not="hello""world"); ⇒ true
# Example in Perl 5'hello'ne'world'# returns 1
# Example in Raku'hello'ne'world'# returns True
# Example in Windows PowerShell"hello"-ne"world"#  returns true

index

[edit]

see#Find

indexof

[edit]

see#Find

instr

[edit]

see#Find

instrrev

[edit]

see#rfind

join

[edit]
Definition join(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 ofsplit.
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[25]
(string-joinarray_of_stringsseparator)Scheme (SRFI 13)
(format nil "~{~a~^separator~}"array_of_strings)Common Lisp
(clojure.string/joinseparatorlist_of_strings)
(apply str (interposeseparatorlist_of_strings))
Clojure
strings.Join(array_of_strings,separator)Go
join(array_of_strings,separator)Seed7
String.concatseparatorlist_of_stringsOCaml
String.concatWithseparatorlist_of_stringsStandard ML
Data.List.intercalateseparatorlist_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 -joinseparator
Windows PowerShell
[array_of_strings componentsJoinedByString:separator]Objective-C (NSString * only)
table.concat(table_of_strings,separator)Lua
{|StringstreamContents: [:stream|collectionOfAnything asStringOn: stream delimiter:separator ]
collectionOfAnything joinUsing:separator
Smalltalk (Squeak,Pharo)
array_of_strings.join(separator«,final_separator»)Cobra
sequence_of_strings.joinWithSeparator(separator)Swift 2.x
1↓∊separatorlist_of_stringsAPL
// Example in C#String.Join("-",{"a","b","c"})// "a-b-c"
" Example in Smalltalk "#('a''b''c')joinUsing:'-'" 'a-b-c' "
# Example in Perl 5join('-',('a','b','c'));# 'a-b-c'
# Example in Raku<a b c>.join('-');# 'a-b-c'
# Example in Python"-".join(["a","b","c"])#  'a-b-c'
# Example in Ruby["a","b","c"].join("-")#  'a-b-c'
; Example in Scheme(use-modules(srfisrfi-13))(string-join'("a""b""c")"-");  "a-b-c"

lastindexof

[edit]

see#rfind

left

[edit]
Definitionleft(string,n) returns string
DescriptionReturns the leftn part of a string. Ifn is greater than the length of the string then most implementations return the whole string (exceptions exist – see code examples). Note that for variable-length encodings such asUTF-8,UTF-16 orShift-JIS, it can be necessary to remove string positions at the end, in order 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(takenstring))Clojure
string[0 ..n]D[26]
string:substr(string,start,length)Erlang
(subseqstring 0n)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,[27]JavaScript
(string-takestringn)Scheme (SRFI 13)
takenstringHaskell
String.extract (string,n, NONE)Standard ML
String.substring 0nOCaml[28]
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[29]
string («FUNCTION» LENGTH(string) -n:n)COBOL
string.substring(0,n)Cobra
nstring.APL
string[0..n]
string[..n]
string.get(0..n)
string.get(..n)
Rust[30]
# Example in Raku"Hello, there!".substr(0,6);# returns "Hello,"
/* Examples in Rexx */left("abcde",3)/* returns "abc"      */left("abcde",8)/* returns "abcde   " */left("abcde",8,"*")/* returns "abcde***" */
; Examples in Scheme(use-modules(srfisrfi-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

[edit]

see#length


length

[edit]
Definitionlength(string) returns an integer number
DescriptionReturns the length of a string (not counting thenull 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 ofUTF-16code unitsVB .NET,C#,Windows PowerShell,F#
chars(string)
string.chars
Number of graphemes (NFG)Raku
codes(string)
string.codes
Number of Unicode code pointsRaku
string.size ORstring.lengthNumber of bytes[31]Ruby
strlen(string)Number of bytesC,PHP
string.length()C++ (STL)
string.lengthCobra,D,JavaScript
string.length()Number ofUTF-16code unitsJava
(string-lengthstring)Scheme
(lengthstring)Common Lisp,ISLISP
(countstring)Clojure
String.lengthstringOCaml
sizestringStandard ML
lengthstringNumber of Unicode code pointsHaskell
string.lengthNumber ofUTF-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()
#string
Lua
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 lengthstringa decimal string giving the number of charactersTcl
stringAPL
string.len()Number of bytesRust[32]
string.chars().count()Number of Unicode code pointsRust[33]
// Examples in C#"hello".Length;// returns 5"".Length;// returns 0
#ExamplesinErlangstring:len("hello").%  returns 5string:len("").%  returns 0
# Examples in Perl 5length("hello");#  returns 5length("");#  returns 0
# Examples in Raku"".chars;chars"";# both return 0"".codes;codes"";# both return 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

[edit]

see#Find


Lowercase

[edit]
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[34]
std.string.toLower(string)D
transform(string.begin(),string.end(),result.begin(), ::tolower)[35]C++[36]
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[37]
strings.ToLower(string)Go
(string-downcasestring)Scheme (R6RS),Common Lisp
(lower-casestring)Clojure
String.lowercasestringOCaml
String.map Char.toLowerstringStandard ML
map Char.toLowerstringHaskell
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[8]
ToLowerCase[string]Mathematica
«FUNCTION» LOWER-CASE(string)COBOL
string.toLowerCobra
string tolowerstringTcl
string.to_lowercase()Rust[38]
// 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){chars[]="Wiki means fast?";for(inti=0;i<sizeof(s)-1;++i){// transform characters in place, one by ones[i]=tolower(s[i]);}printf(string);// "wiki means fast?"return0;}
# Example in Raku"Wiki means fast?".lc;# "wiki means fast?"


mid

[edit]

see#substring


partition

[edit]
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
splitseparator,string, 2
string.split(separator, 2 )
RakuSeparator does not have to be a regular expression
# Examples in Python"Spam eggs spam spam and ham".partition('spam')# ('Spam eggs ', 'spam', ' spam and ham')"Spam eggs spam spam and ham".partition('X')# ('Spam eggs spam spam and ham', "", "")
# Examples in Perl 5 / Rakusplit/(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

[edit]
Definitionreplace(string,find,replace) returns string
DescriptionReturns a string withfind occurrences changed toreplace.
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[39]
string.replaceAll(find_regex,replace)[40]Java
string.gsub(find,replace)Ruby
string =~ s/find_regex/replace/g[40]Perl 5
string.subst(find,replace, :g)Raku
string.replace(find,replace, "g")[41]
string.replace(/find_regex/g,replace)[40]
JavaScript
echo "string" |sed 's/find_regex/replace/g'[40]Unix
${string_param//find_pattern/replace}Bash
string.replace(find,replace)
string -replacefind_regex,replace[40]
Windows PowerShell
Str.global_replace (Str.regexp_stringfind)replacestringOCaml
[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 {findreplace}stringTcl
StringReplace[string,find ->replace]Mathematica
strings.Replace(string,find,replace, -1)Go
INSPECTstring REPLACING ALL/LEADING/FIRSTfind BYreplaceCOBOL
find_regex ⎕Rreplace_regexstringAPL
// 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"
//ExamplesinRaku"effffff".subst("f","jump", :g);# returns "ejumpjumpjumpjumpjumpjump""blah".subst("z","y", :g);# returns "blah"
' 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

[edit]
Definitionreverse(string)
DescriptionReverses the order of the characters in the string.
FormatLanguages
reversestringPerl 5,Haskell
flipstring
string.flip
Raku
lists:reverse(string)Erlang
strrev(string)PHP
string[::-1]Python
(string-reversestring)Scheme (SRFI 13)
(reversestring)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 (explodestring))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 reversestringTcl
stringAPL
string.chars().rev().collect::<String>()Rust[42]
echostring | revUnix
" Example in Smalltalk "'hello'reversed" returns 'olleh' "
# Example in Perl 5reverse"hello"# returns "olleh"
# Example in Raku"hello".flip# returns "olleh"
# Example in Python"hello"[::-1]# returns "olleh"
; Example in Scheme(use-modules(srfisrfi-13))(string-reverse"hello"); returns "olleh"

rfind

[edit]
Definitionrfind(string,substring) returns integer
DescriptionReturns the position of the start of the last occurrence ofsubstring instring. If thesubstring 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»)Perl 5returns −1
rindex(string,substring«,startpos»)
string.rindex(substring«,startpos»)
RakureturnsNil
strrpos(string,substring«,startpos»)PHPreturnsFALSE
string.rfind(substring«,startpos»)C++ (STL)returnsstd::string::npos
std.string.rfind(string,substring)Dreturns −1
string.rfind(substring«,startpos«,endpos»»)Pythonreturns −1
string.rindex(substring«,startpos«,endpos»»)raisesValueError
rpos(string,substring«,startpos»)Seed7returns 0
string.rindex(substring«,startpos»)Rubyreturnsnil
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
(searchsubstringstring :from-end t)Common LispreturnsNIL
[string rangeOfString:substring options:NSBackwardsSearch].locationObjective-C (NSString * only)returnsNSNotFound
Str.search_backward (Str.regexp_stringsubstring)string (Str.lengthstring - 1)OCamlraisesNot_found
string.match(string, '.*()'..substring)
string:match('.*()'..substring)
Luareturnsnil
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 lastsubstring string startposTclreturns −1
(⌽<\substring'string')1APLreturns −1
string.rfind(substring)Rust[43]returnsNone
; Examples in Common Lisp(search"e""Hello mate":from-endt);  returns 9(search"z""word":from-endt);  returns NIL
// Examples in C#"Hello mate".LastIndexOf("e");// returns 9"Hello mate".LastIndexOf("e",4);// returns 1"word".LastIndexOf("z");// returns -1
# Examples in Perl 5rindex("Hello mate","e");# returns 9rindex("Hello mate","e",4);# returns 1rindex("word","z");# returns -1
# Examples in Raku"Hello mate".rindex("e");# returns 9"Hello mate".rindex("e",4);# returns 1"word".rindex('z');# returns Nil
' Examples in Visual BasicInStrRev("Hello mate","e")'  returns 10InStrRev(5,"Hello mate","e")'  returns 2InStrRev("word","z")'  returns 0


right

[edit]
Definitionright(string,n) returns string
DescriptionReturns the rightn part of a string. Ifn 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 ofstring)C
string.Substring(string.Length()-n)C#
string[len(string)-n:]Go
string.substring(string.length()-n)Java
string.slice(-n)JavaScript[44]
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} (note the space after the colon)Bash
string[n]Pick Basic
(string-take-rightstringn)Scheme (SRFI 13)
string[-n..-1]Ruby
string[$-n .. $]D[45]
String.substring (String.lengthstring -n)nOCaml[28]
string.sub(string, -n)
(string):sub(-n)
Lua
string last:nSmalltalk (Squeak,Pharo)
StringTake[string, -n]Mathematica[29]
string (1:n)COBOL
¯nstring.APL
string[n..]
string.get(n..)
Rust[30]
// Examples in Java; extract rightmost 4 charactersStringstr="CarDoor";str.substring(str.length()-4);// returns 'Door'
# Examples in Raku"abcde".substr(*-3);# returns "cde""abcde".substr(*-8);# 'out of range' error
/* Examples in Rexx */right("abcde",3)/* returns "cde"      */right("abcde",8)/* returns "   abcde" */right("abcde",8,"*")/* returns "***abcde" */
; Examples in Scheme(use-modules(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"


rpartition

[edit]
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

[edit]

see#substring


split

[edit]
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. Iflimit is given, afterlimit – 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 ofjoin.
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-tokenizestring« charset« start« end»»»)Scheme (SRFI 13)
Split(string,sepchars«,limit»)VB
string.Split(sepchars«,limit«,options»»)VB .NET,C#,F#
string -splitseparator«,limit«,options»»Windows PowerShell
Str.split (Str.regexp_stringseparator)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
splitstring separatorTcl
(separatorstring)⊂string in APL2
separator(≠⊆⊢)string in Dyalog APL 16.0
APL
string.split(separator)

string.split(limit,separator)

Rust[46]
// 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 Pascal }varlStrings:TStringList;lStr:string;beginlStrings:=TStringList.Create;lStrings.Delimiter:=',';lStrings.DelimitedText:='abc,defgh,ijk';lStr:=lStrings.Strings[0];// 'abc'lStr:=lStrings.Strings[1];// 'defgh'lStr:=lStrings.Strings[2];// 'ijk'end;
# Examples in Perl 5split(/spam/,'Spam eggs spam spam and ham');# ('Spam eggs ', ' ', ' and ham')split(/X/,'Spam eggs spam spam and ham');# ('Spam eggs spam spam and ham')
# Examples in Raku'Spam eggs spam spam and ham'.split(/spam/);# (Spam eggs     and ham)split(/X/,'Spam eggs spam spam and ham');# (Spam eggs spam spam and ham)


sprintf

[edit]

see#Format

strip

[edit]

see#trim


strcmp

[edit]

see#Compare (integer result)


substring

[edit]
SeeCharAt for base of startpos/endpos.
Definitionsubstring(string,startpos,endpos) returns string
substr(string,startpos,numChars) returns string
DescriptionReturns a substring ofstring between starting atstartpos andendpos, or starting atstartpos of lengthnumChars. The resulting string is truncated if there are fewer thannumChars characters beyond the starting point.endpos represents the index after the last character in the substring. Note that for variable-length encodings such asUTF-8,UTF-16 orShift-JIS, it can be necessary to remove string positions at the end, in order 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,[47][48]PHP[47][48]
substr(string,startpos,numChars)
string.substr(startpos,numChars)
Raku[49][50]
substr(string,startpos «,numChars,padChar»)Rexx
string[startpos:endpos]Cobra,Python,[47][51]Go
string[startpos,numChars]Pick Basic
string[startpos,numChars]
string[startpos ..endpos-1]
string[startpos ...endpos]
Ruby[47][51]
string[startpos ..endpos]
string[startpos lennumChars]
Seed7
string.slice(startpos«,endpos»)JavaScript[47][51]
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)
(substringstringstartposendpos)Scheme
(subseqstringstartposendpos)Common Lisp
(subseqstringstartposendpos)ISLISP
String.substringstartposnumCharsOCaml
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
takenumChars $ dropstartposstringHaskell
[string substringWithRange:NSMakeRange(startpos,numChars)]Objective-C (NSString * only)
string.[startpos..endpos]F#
string.sub(string,startpos,endpos)
(string):sub(startpos,endpos)
Lua[47][51]
string copyFrom:startpos to:endposSmalltalk
string(startpos:endpos)Fortran
SUBSTRING(string FROMstartpos «FORnumChars»)SQL
StringTake[string, {startpos,endpos}]Mathematica[47][51]
string (startpos:numChars)COBOL
${string_param:startpos:numChars}Bash
string rangestring startpos endposTcl
string[startpos..endpos]
string.get(startpos..endpos)
Rust[30]
// 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"12); returns "b"(subseq"abc"2); returns "c"
% Examples in Erlangstring:substr("abc",2,1).%  returns "b"string:substr("abc",2).%  returns "bc"
# Examples in Perl 5substr("abc",1,1);#  returns "b"substr("abc",1);#  returns "bc"
# Examples in Raku"abc".substr(1,1);#  returns "b""abc".substr(1);#  returns "bc"
# Examples in Python"abc"[1:2]#  returns "b""abc"[1:3]#  returns "bc"
/* Examples in Rexx */substr("abc",2,1)/* returns "b"      */substr("abc",2)/* returns "bc"     */substr("abc",2,6)/* returns "bc    " */substr("abc",2,6,"*")/* returns "bc****" */


Uppercase

[edit]
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_ti=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)[35]C++[52]
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
PARSEUPPERVARSrcVarDstVar
Rexx
string.upper()Python
upcase(string)Pick Basic
string.upcaseRuby[37]
strings.ToUpper(string)Go
(string-upcasestring)Scheme,Common Lisp
String.uppercasestringOCaml
String.map Char.toUpperstringStandard ML
map Char.toUpperstringHaskell
string.toUpperCase()Java,JavaScript
string.uppercase()Kotlin[53]
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 toupperstringTcl
string.to_uppercase()Rust[54]
// Example in C#"Wiki means fast?".ToUpper();// "WIKI MEANS FAST?"
# Example in Perl 5uc("Wiki means fast?");# "WIKI MEANS FAST?"
# Example in Rakuuc("Wiki means fast?");# "WIKI MEANS FAST?""Wiki means fast?".uc;# "WIKI MEANS FAST?"
/* Example in Rexx */translate("Wiki means fast?")/* "WIKI MEANS FAST?" *//* Example #2 */A='This is an example.'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?"

trim

[edit]
Main article:Trim (programming)

trim orstrip 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
(.trimstring)Clojure
sequence [ predicate? ] trimFactor
(string-trim'(#\Space#\Tab#\Newline)string)Common Lisp
(string-trimstring)Scheme
string.trim()Java,JavaScript (1.8.1+, Firefox 3.5+),Rust[55]
Trim(String)Pascal,[56]QBasic,Visual Basic,Delphi
string.strip()Python
strings.Trim(string,chars)Go
LTRIM(RTRIM(String))OracleSQL,T-SQL
strip(string [,option,char])REXX
string:strip(string [,option,char])Erlang
string.strip
string.lstrip
string.rstrip
Ruby
string.trimRaku
trim(string)PHP,Raku
[stringstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]]Objective-C usingCocoa
string withBlanksTrimmed
string withoutSpaces
string withoutSeparators
Smalltalk (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.trimstringOCaml 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

[edit]

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

[edit]

InAWK, one can use regular expressions to trim:

ltrim(v)=gsub(/^[ \t]+/,"",v)rtrim(v)=gsub(/[ \t]+$/,"",v)trim(v)=ltrim(v);rtrim(v)

or:

functionltrim(s){sub(/^[ \t]+/,"",s);returns}functionrtrim(s){sub(/[ \t]+$/,"",s);returns}functiontrim(s){returnrtrim(ltrim(s));}

C/C++

[edit]

There is no standard trim function in C or C++. Most of the available string libraries[57] for C contain code which implements trimming, or functions that significantly ease an efficient implementation. The function has also often been calledEatWhitespace in some non-standard C libraries.

In C, programmers often combine a ltrim and rtrim to implement trim:

#include<ctype.h>#include<string.h>voidrtrim(char*str){char*s;s=str+strlen(str);while(--s>=str){if(!isspace(*s)){break;}*s=0;}}voidltrim(char*str){size_tn;n=0;while(str[n]&&isspace((unsignedchar)str[n])){n++;}memmove(str,str+n,strlen(str)-n+1);}voidtrim(char*str){rtrim(str);ltrim(str);}

Theopen source C++ libraryBoost has several trim variants, including a standard one:[58]

#include<boost/algorithm/string/trim.hpp>trimmed=boost::algorithm::trim_copy("string");

With boost's function named simplytrim the input sequence is modified in-place, and returns no result.

Anotheropen source C++ libraryQt, has several trim variants, including a standard one:[59]

#include<QString>trimmed=s.trimmed();

TheLinux 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 usesstrim() instead ofstrstrip() to avoid false warnings.[60]

Haskell

[edit]

A trim algorithm inHaskell:

importData.Char(isSpace)trim::String->Stringtrim=f.fwheref=reverse.dropWhileisSpace

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

J

[edit]

The trim algorithm inJ is afunctional description:

trim=.#~[:(+./\*.+./\.)' '&~:

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

JavaScript

[edit]

There is a built-in trim function in JavaScript 1.8.1 (Firefox 3.5 and later), and the ECMAScript 5 standard. In earlier versions it can be added to the String object's prototype as follows:

String.prototype.trim=function(){returnthis.replace(/^\s+/g,"").replace(/\s+$/g,"");};

Perl

[edit]

Perl 5 has no built-in trim function. However, the functionality is commonly achieved usingregular 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 isStripLTSpace inString::Strip fromCPAN.

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

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

InRaku, the upcoming sister language of Perl, strings have atrim method.

Example:

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

Tcl

[edit]

TheTclstring command has three relevant subcommands:trim,trimright andtrimleft. 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:

setstringonomatopoeiasettrimmed[stringtrim$stringaeiou];# result is nomatopsetr_trimmed[stringtrimright$stringaeiou];# result is onomatopsetl_trimmed[stringtrimleft$stringaeiou];# result is nomatopoeia

XSLT

[edit]

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

Example:

<xsl:variablename='trimmed'><xsl:value-ofselect='normalize-space(string)'/></xsl:variable>

XSLT 2.0 includes regular expressions, providing another mechanism to perform string trimming.

Another XSLT technique for trimming is to utilize the XPath 2.0substring() function.

References

[edit]
  1. ^abcdethe index can be negative, which then indicates the number of places before the end of the string.
  2. ^In Rust, thestr::chars method iterates over code points and thestd::iter::Iterator::nth method on iterators returns the zero-indexed nth value from the iterator, orNone.
  3. ^the index cannot be negative, use*-N where N indicate the number of places before the end of the string.
  4. ^In C++, the overloadedoperator<=> method on astring returns astd::strong_ordering object (otherwisestd::weak_ordering):less,equal (same asequivalent), orgreater.
  5. ^returns LESS, EQUAL, or GREATER
  6. ^returns LT, EQ, or GT
  7. ^returns.TRUE. or.FALSE.. These functions are based on the ASCII collating sequence.
  8. ^abIBM extension.
  9. ^In Rust, theOrd::cmp method on astring returns anOrdering:Less,Equal, orGreater.
  10. ^The original REXX used ¬ for Logical Not, ANSI Rexx uses \, some implementations accept ~ or ^, and non-EBCDIC implementations vary as to whether ¬ is at code point AA or AC.
  11. ^The original PL/I used ¬ for Logical Not, some implementations expect ^, and non-EBCDIC implementations vary as to whether ¬ is at code point AA or AC.
  12. ^abcdefIn Rust, the operators== and!= and the methodseq,ne are implemented by thePartialEq trait, and the operators<,>,<=,>= and the methodslt,gt,le,ge are implemented by thePartialOrd trait.
  13. ^The operators use the compiler's default collating sequence.
  14. ^modifiesstring1, which must have enough space to store the result
  15. ^In Rust, the+ operator is implemented by theAdd trait.
  16. ^See thestr::contains method.
  17. ^See thestd::basic_string::contains method.
  18. ^abstartpos is IBM extension.
  19. ^abSee thestr::find method.
  20. ^startpos is IBM extension.
  21. ^"scan in Fortran Wiki". Fortranwiki.org. 2009-04-30. Retrieved2013-08-18.
  22. ^"verify in Fortran Wiki". Fortranwiki.org. 2012-05-03. Retrieved2013-08-18.
  23. ^formatstring must be a fixed literal at compile time for it to have the correct type.
  24. ^Seestd::format, which is imported by the Rustprelude so that it can be used under the nameformat.
  25. ^See theslice::join method.
  26. ^if n is larger than the length of the string, then in Debug mode ArrayRangeException is thrown, in Release mode, the behaviour isunspecified.
  27. ^if n is larger than the length of the string, Java will throw an IndexOutOfBoundsException
  28. ^abif n is larger than length of string, raises Invalid_argument
  29. ^abif n is larger than length of string, throw the message "StringTake::take:"
  30. ^abcIn Rust, strings are indexed in terms of byte offsets and there is a runtime panic if the index is out of bounds or if it would result in invalidUTF-8. A&str (string reference) can beindexed by various types of ranges, includingRange (0..n),RangeFrom (n..), andRangeTo (..n) because they all implement theSliceIndex trait withstr being the type being indexed.Thestr::get method is the non-panicking way to index. It returnsNone in the cases in which indexing would panic.
  31. ^Ruby lacks Unicode support
  32. ^See thestr::len method.
  33. ^In Rust, thestr::chars method iterates over code points and thestd::iter::Iterator::count method on iterators consumes the iterator and returns the total number of elements in the iterator.
  34. ^operates on one character
  35. ^abThetransform function exists in thestd:: namespace. You must include the<algorithm> header file to use it. Thetolower andtoupper functions are in the global namespace, obtained by the<ctype.h> header file. Thestd::tolower andstd::toupper names are overloaded and cannot be passed tostd::transform without a cast to resolve a function overloading ambiguity, e.g.std::transform(string.begin(),string.end(),result.begin(), (int (*)(int))std::tolower);
  36. ^std::string only, result is stored in stringresult which is at least as long asstring, and may or may not bestring itself
  37. ^abonly ASCII characters as Ruby lacks Unicode support
  38. ^See thestr::to_lowercase method.
  39. ^See thestr::replace method.
  40. ^abcdeThe "find" string in this construct is interpreted as aregular expression. Certain characters have special meaning in regular expressions. If you want to find a string literally, you need to quote the special characters.
  41. ^third parameter is non-standard
  42. ^In Rust, thestr::chars method iterates over code points, thestd::iter::Iterator::rev method on reversible iterators (std::iter::DoubleEndedIterator) creates a reversed iterator, and thestd::iter::Iterator::collect method consumes the iterator and creates a collection (which here is specified as aString with theturbofish syntax) from the iterator's elements.
  43. ^See thestr::rfind method.
  44. ^"Annotated ES5". Es5.github.com. Archived fromthe original on 2013-01-28. Retrieved2013-08-18.
  45. ^if n is larger than length of string, then in Debug mode ArrayRangeException is thrown, and unspecified behaviour in Release mode
  46. ^See thestr::split andstr::rsplit methods.
  47. ^abcdefgstartpos can be negative, which indicates to start that number of places before the end of the string.
  48. ^abnumChars can be negative, which indicates to end that number of places before the end of the string.
  49. ^startpos cannot be negative, use* - startpos to indicate to start that number of places before the end of the string.
  50. ^numChars cannot be negative, use* - numChars to indicate to end that number of places before the end of the string.
  51. ^abcdeendpos can be negative, which indicates to end that number of places before the end of the string.
  52. ^std::string only, result is stored in stringresult which is at least as long asstring, and may or may not bestring itself
  53. ^"uppercase - Kotlin Programming Language".Kotlin. Retrieved9 November 2024.
  54. ^In Rust, thestr::to_uppercase method returns a newly allocatedString with any lowercase characters changed to uppercase ones following the Unicode rules.
  55. ^In Rust, thestr::trim method returns a reference to the original&str.
  56. ^"Trim – GNU Pascal priručnik". Gnu-pascal.de. Retrieved2013-08-24.
  57. ^"String library comparison". And.org. Retrieved2013-08-24.
  58. ^"Usage – 1.54.0". Boost.org. 2013-05-22. Retrieved2013-08-24.
  59. ^[1]Archived August 2, 2009, at theWayback Machine
  60. ^dankamongmen."sprezzos-kernel-packaging/changelog at master · dankamongmen/sprezzos-kernel-packaging · GitHub". Github.com. Retrieved2016-05-29.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Comparison_of_programming_languages_(string_functions)&oldid=1333190922"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp