{{Short description|none}} {{Redirect|String functions|string functions in formal language theory|String operations}} {{Further|Comparison of programming languages}} <!-- TO CONTRIBUTORS: Thanks to all who have submitted code samples from various programming languages. When adding code samples, *please* include no extraneous characters or symbols that are not part of a programming language, such as interactive command prompts. This can needlessly confuse general readers.
All code samples should at least be able to compile without error, when copied and pasted directly into a source code file. --> {{ProgLangCompare}} String functions are used in computer programming languages to manipulate a string or query information about a string (some do both).
Most programming languages that have a string datatype will have some string functions although there may be other low-level ways within each language to handle strings directly. In object-oriented languages, string functions are often implemented as properties and methods of string objects. In functional and list-based languages a string is represented as a list (of character codes), therefore all list-manipulation procedures could be considered string functions. However such languages may implement a subset of explicit string-specific functions as well.
For function that manipulate strings, modern object-oriented languages, like C# and Java have immutable strings and return a copy (in newly allocated dynamic memory), while others, like C manipulate the original string unless the programmer copies data to a new string. See for example Concatenation below.
The most basic example of a string function is the <code>length(string)</code> function. This function returns the length of a string literal.
:e.g. <code>length("hello world")</code> would return 11.
Other languages may have string functions with similar or exactly the same syntax or parameters or outcomes. For example, in many languages the length function is usually represented as ''len(string)''. The below list of common functions aims to help limit this confusion.
==Common string functions (multi language reference)== {{unreferenced section|date=July 2013}} String functions common to many languages are listed below, including the different names used. The below list of common functions aims to help programmers find the equivalent function in a language. String concatenation and regular expressions are handled in separate pages. Statements in guillemets (« … ») are optional.<ref>{{Cite web |title=W3Schools Online Web Tutorials |url=https://www.w3schools.com/ |access-date=2026-04-14 |website=www.w3schools.com |language=en-US}}</ref> <!-- When giving literal examples, name the language used, as different languages use different syntax. List in alphabetic order, please. -->
===CharAt=== <!-- startsection --> {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>charAt(string,integer)</code> returns character. |- ! Description | Returns character at index in the string. |- ! Equivalent | See substring of length 1 character. |} {{sort-under}} {| class="wikitable sortable sort-under" |- style="text-align:left;" ! Format !! Languages !! Base<br/>index |- | <code>''string''[''i'']</code> |ALGOL 68, APL, Julia, Pascal, Object Pascal (Delphi), Seed7 |1 |- | <code>''string''[''i'']</code> |C, C++, C#, Cobra, D, FreeBASIC, Go, Python,<ref name="at1"/> PHP, Ruby,<ref name="at1"/> Windows PowerShell, JavaScript, APL |0 |- | <code>''string''{''i''}</code> |PHP (deprecated in 5.3) |0 |- | <code>''string''(''i'')</code> |Ada |≥1 |- | <code>Mid(''string'',i,1)</code> |VB |1 |- | <code>MID$(''string'',i,1)</code> |BASIC |1 |- | <code>''string''.Chars(''i'')</code> |VB.NET |0 |- | <code>''string''(''i'':''i'')</code> |Fortran |1 |- | <code>''string''.charAt(''i'')</code> |Java, JavaScript |0 |- | <code>''string''.[''i'']</code> |OCaml, F# |0 |- | <code>''string''.chars().nth(''i'')</code> |Rust<ref>In Rust, the [https://doc.rust-lang.org/std/primitive.str.html#method.chars <code>str::chars</code>] method iterates over code points and the [https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.nth <code>std::iter::Iterator::nth</code>] method on iterators returns the zero-indexed nth value from the iterator, or <code>None</code>.</ref> |0 |- | <code>''string''[''i'',''1'']</code> |Pick Basic |1 |- | <code>String.sub (''string'', ''i'')</code> |Standard ML |0 |- | <code>''string'' !! ''i''</code> |Haskell |0 |- | <code>(string-ref ''string'' ''i'')</code> |Scheme |0 |- | <code>(char ''string'' ''i'')</code> |Common Lisp |0 |- | <code>(elt ''string'' ''i'')</code> |ISLISP |0 |- | <code>(get ''string'' ''i'')</code> |Clojure |0 |- | <code>substr(''string'', ''i'', 1)</code> |Perl 5<ref name="at1"/> |0 |- | <code>substr(''string'', ''i'', 1)</code><br><code>string.substr(''i'', 1)</code> |Raku<ref name="at2"/> |0 |- | <code>substr(''string'', ''i'', 1)</code> |PL/I |1 |- | <code>substr(''string'', ''i'', 1)</code> |REXX |1 |- | <code>''string''.at(''i'')</code> |C++ (STL) (w/ bounds checking) |0 |- | <code>lists:nth(''i'', ''string'')</code> |Erlang |1 |- | <code>[''string'' characterAtIndex:''i'']</code> |Objective-C (<code>NSString *</code> only) |0 |- | <code>string.sub(''string'', ''i'', ''i'')</code><br><code>(''string''):sub(''i'', ''i'')</code> |Lua<ref name="at1"/> |1 |- | <code>''string'' at: ''i''</code> |Smalltalk (w/ bounds checking) |1 |- | <code>string index ''string i''</code> |Tcl |0 |- | <code>StringTake[''string'', {''i''}]</code> |Mathematica, Wolfram Language<ref name="at1"/> |1 |- | <code>''string''@''i''</code> |Eiffel |1 |- | <code>''string'' (''i'':1)</code> | COBOL |1 |- | <code>${''string_param'':''i'':1}</code> | Bash |0 |- | <code>''i''⌷''string''</code> | APL |0 or 1 |}
<syntaxhighlight lang="pascal"> { Example in Pascal } var MyStr: string = 'Hello, World'; MyChar: Char; begin MyChar := MyStr[2]; // 'e' </syntaxhighlight>
<pre> # Example in ALGOL 68 # "Hello, World"[2]; // 'e' </pre>
<syntaxhighlight lang="c"> // Example in C #include <stdio.h>
char myStr1[] = "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)' </syntaxhighlight>
<syntaxhighlight lang="c++"> import std;
using std::string;
char myStr1[] = "Hello(1), World(1)"; string myStr2 = "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)' </syntaxhighlight>
<syntaxhighlight lang="csharp"> // Example in C# "Hello, World"[2]; // 'l' </syntaxhighlight>
<syntaxhighlight lang="perl"> # Example in Perl 5 substr("Hello, World", 1, 1); # 'e' </syntaxhighlight>
<syntaxhighlight lang="python"> # Examples in Python "Hello, World"[2] # 'l' "Hello, World"[-3] # 'r' </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku "Hello, World".substr(1, 1); # 'e' </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Example in Visual Basic Mid("Hello, World",2,1) </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Example in Visual Basic .NET "Hello, World".Chars(2) ' "l"c </syntaxhighlight>
<syntaxhighlight lang="smalltalk"> " Example in Smalltalk " 'Hello, World' at: 2. "$e" </syntaxhighlight>
<syntaxhighlight lang="rust"> //Example in Rust "Hello, World".chars().nth(2); // Some('l') </syntaxhighlight> <!-- endsection -->
===Compare (integer result)=== {{see also|Three-way comparison}} {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>compare(string<sub>1</sub>,string<sub>2</sub>)</code> returns integer. |- ! Description | Compares two strings to each other. If they are equivalent, a zero is returned. Otherwise, most of these routines will return a positive or negative result corresponding to whether string<sub>1</sub> is lexicographically greater than, or less than, respectively, than string<sub>2</sub>. 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. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>IF ''string<sub>1</sub>''<''string<sub>2</sub>'' THEN -1 ELSE ABS (''string<sub>1</sub>''>''string<sub>2</sub>'') FI</code> |ALGOL 68 |- | <code>cmp(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |Python 2 |- | <code>(''string<sub>1</sub>'' > ''string<sub>2</sub>'') - (''string<sub>1</sub>'' < ''string<sub>2</sub>'')</code> |Python |- | <code>strcmp(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |C, PHP |- | <code>std.string.cmp(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |D |- | <code>StrComp(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |VB, Object Pascal (Delphi) |- | <code>''string<sub>1</sub>'' cmp ''string<sub>2</sub>''</code> |Perl, Raku |- | <code>''string<sub>1</sub>'' compare: ''string<sub>2</sub>''</code> |Smalltalk (Squeak, Pharo) |- | <code>''string<sub>1</sub>'' <=> ''string<sub>2</sub>''</code> |Ruby, C++ (STL, C++20)<ref>In C++, the overloaded [https://en.cppreference.com/w/cpp/language/operator_comparison#Three-way%20comparison <code>operator<=></code>] method on a [https://en.cppreference.com/w/cpp/string/basic_string string] returns a [https://en.cppreference.com/w/cpp/utility/compare/strong_ordering <code>std::strong_ordering</code>] object (otherwise <code>std::weak_ordering</code>): <code>less</code>, <code>equal</code> (same as <code>equivalent</code>), or <code>greater</code>.</ref> |- | <code>''string<sub>1</sub>''.compare(''string<sub>2</sub>'')</code> |C++ (STL), Swift (Foundation) |- | <code>compare(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |Rexx, Seed7 |- | <code>compare(''string<sub>1</sub>'', ''string<sub>2</sub>'', ''pad'')</code> |Rexx |- | <code>CompareStr(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |Pascal, Object Pascal (Delphi) |- | <code>''string<sub>1</sub>''.compareTo(''string<sub>2</sub>'')</code> |Cobra, Java |- | <code>''string<sub>1</sub>''.CompareTo(''string<sub>2</sub>'')</code> |VB .NET, C#, F# |- | <code>(compare ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Clojure |- | <code>(string= ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Common Lisp |- | <code>(string-compare ''string<sub>1</sub>'' ''string<sub>2</sub>'' ''p<'' ''p='' ''p>'')</code> |Scheme (SRFI 13) |- | <code>(string= ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |ISLISP |- | <code>compare ''string<sub>1</sub>'' ''string<sub>2</sub>''</code> |OCaml |- | <code>String.compare (''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |Standard ML<ref>returns LESS, EQUAL, or GREATER</ref> |- | <code>compare ''string<sub>1</sub>'' ''string<sub>2</sub>''</code> |Haskell<ref>returns LT, EQ, or GT</ref> |- | <code>[string]::Compare(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |Windows PowerShell |- | <code>[''string<sub>1</sub>'' compare:''string<sub>2</sub>'']</code> |Objective-C (<code>NSString *</code> only) |- | <code>LLT(''string<sub>1</sub>'',''string<sub>2</sub>'')</code><br><code>LLE(''string<sub>1</sub>'',''string<sub>2</sub>'')</code><br><code>LGT(''string<sub>1</sub>'',''string<sub>2</sub>'')</code><br><code>LGE(''string<sub>1</sub>'',''string<sub>2</sub>'')</code> |Fortran<ref>returns <code>.TRUE.</code> or <code>.FALSE.</code>. These functions are based on the ASCII collating sequence.</ref> |- | <code>''string<sub>1</sub>''.localeCompare(''string<sub>2</sub>'')</code> |JavaScript |- | <code>{{codett|2=go|bytes.Compare([]byte(}}''string<sub>1</sub>''{{codett|2=go|), []byte(}}''string<sub>2</sub>''))</code> |Go |- | <code>string compare ''string<sub>1</sub>'' ''string<sub>2</sub>''</code> |Tcl |- | <code>compare(''string<sub>1</sub>'',''string<sub>2</sub>'',''count'')</code> |PL/I<ref name="lower1">IBM extension.</ref> |- | <code>''string<sub>1</sub>''.cmp(''string<sub>2</sub>'')</code> | Rust<ref>In Rust, the [https://doc.rust-lang.org/std/cmp/trait.Ord.html#tymethod.cmp <code>Ord::cmp</code>] method on a [https://doc.rust-lang.org/std/primitive.str.html#impl-Ord string] returns an [https://doc.rust-lang.org/std/cmp/enum.Ordering.html <code>Ordering</code>]: <code>Less</code>, <code>Equal</code>, or <code>Greater</code>.</ref> |}
<syntaxhighlight lang="perl"> # Example in Perl 5 "hello" cmp "world"; # returns -1 </syntaxhighlight>
<syntaxhighlight lang="python"> # Example in Python cmp("hello", "world") # returns -1 </syntaxhighlight>
<syntaxhighlight lang="raku"> # Examples in Raku "hello" cmp "world"; # returns Less "world" cmp "hello"; # returns More "hello" cmp "hello"; # returns Same </syntaxhighlight>
<syntaxhighlight lang="rexx"> /** Example in Rexx */ compare("hello", "world") /* returns index of mismatch: 1 */ </syntaxhighlight>
<syntaxhighlight lang="scheme"> ; Example in Scheme (use-modules (srfi srfi-13)) ; returns index of mismatch: 0 (string-compare "hello" "world" values values values) </syntaxhighlight> <!-- endsection -->
===Compare (relational operator-based, Boolean result)=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>string<sub>1</sub> OP string<sub>2</sub></code> OR <code>(compare string<sub>1</sub> string<sub>2</sub>)</code> returns Boolean. |- ! Description | Lexicographically compares two strings using a relational operator or function. Boolean result returned. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1= =, <>, <, >, <=}} and {{mono|1=>=}} |Pascal, Object Pascal (Delphi), OCaml, Seed7, Standard ML, BASIC, VB, VB .NET, F# |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1= =, /=, ≠, <, >, <=, ≤}} and {{mono|1=≥}}; Also: {{mono|1=EQ, NE, LT, LE, GE}} and {{mono|1=GT}} |ALGOL 68 |- | <code>(stringOP? ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code>, where <code>OP</code> can be any of {{mono|1==, -ci=, <, -ci<, >, -ci>, <=, -ci<=, >=}} and {{mono|1=-ci>=}} (operators starting with '<code>-ci</code>' are case-insensitive) |Scheme |- | <code>(stringOP ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code>, where <code>OP</code> can be any of {{mono|1==, -ci=, <>, -ci<>, <, -ci<, >, -ci>, <=, -ci<=, >=}} and {{mono|1=-ci>=}} (operators starting with '{{mono|1=-ci}}' are case-insensitive) |Scheme (SRFI 13) |- | <code>(stringOP ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code>, where <code>OP</code> can be any of {{mono|1==, -equal, /=, -not-equal, <, -lessp, >, -greaterp, <=, -not-greaterp, >=}} and {{mono|1=-not-lessp}} (the verbal operators are case-insensitive) |Common Lisp |- | <code>(stringOP ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code>, where <code>OP</code> can be any of {{mono|1==, /=, <, >, <=,}} and {{mono|1=>=}} |ISLISP |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1= =, \=, <, >, <=}} and {{mono|1=>=}}<ref name=LnotREXX>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.</ref> |Rexx |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1= =, ¬=, <, >, <=, >=, ¬<}} and {{mono|1=¬>}}<ref name=LnotPLI>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.</ref> |PL/I |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1==, /=, <, >, <=}} and {{mono|1=>=}} |Ada |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1===, /=, <, >, =<}} and {{mono|1=>=}} |Erlang |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1===, /=, <, >, <=}} and {{mono|1=>=}} |Haskell |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1=''eq'', ''ne'', ''lt'', ''gt'', ''le''}} and {{mono|1=''ge''}} |Perl, Raku |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1===, !=, <, >, <=}} and {{mono|1=>=}} |C++ (STL), C#, D, Go, JavaScript, Python, PHP, Ruby, Rust,<ref name="Rust compare">In Rust, the operators {{mono|1===}} and {{mono|1=!=}} and the methods <code>eq</code>, <code>ne</code> are implemented by the [https://doc.rust-lang.org/std/primitive.str.html#impl-PartialEq%3Cstr%3E <code>PartialEq</code>] trait, and the operators {{mono|1=<}}, {{mono|1=>}}, {{mono|1=<=}}, {{mono|1=>=}} and the methods <code>lt</code>, <code>gt</code>, <code>le</code>, <code>ge</code> are implemented by the [https://doc.rust-lang.org/std/primitive.str.html#impl-PartialOrd%3Cstr%3E <code>PartialOrd</code>] trait.</ref> Swift |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1=-eq, -ceq, -ne, -cne, -lt, -clt, -gt, -cgt, -le, -cle, -ge,}} and {{mono|1=-cge}} (operators starting with '{{mono|1=c}}' are case-sensitive) |Windows PowerShell |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1===, ~=, <, >, <=}} and {{mono|1=>=}} |Lua |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1==, ~=, <, >, <=}} and {{mono|1=>=}} |Smalltalk |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code>, where <code>OP</code> can be any of {{mono|1===, /=, <, >, <=}} and {{mono|1=>=; Also: .EQ., .NE., .LT., .LE., .GT.}} and {{mono|1=.GE.}} |Fortran<ref>The operators use the compiler's default collating sequence.</ref> |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code> where <code>OP</code> can be any of {{mono|1==, <>, <, >, <=, >=}} as well as worded equivalents | COBOL |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code> where <code>OP</code> can be any of {{mono|1===, <>, <, >, <=}} and {{mono|1=>=}} | Cobra |- | <code>''string<sub>1</sub>'' OP ''string<sub>2</sub>''</code> 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 |- | <code>''string<sub>1</sub>''.METHOD(''string<sub>2</sub>'')</code> where <code>METHOD</code> is any of <code>eq</code>, <code>ne</code>, <code>gt</code>, <code>lt</code>, <code>ge</code>, <code>le</code> | Rust<ref name="Rust compare" /> |}
<syntaxhighlight lang="erlang"> % Example in Erlang "hello" > "world". % returns false </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku "art" gt "painting"; # returns False "art" lt "painting"; # returns True </syntaxhighlight>
<syntaxhighlight lang="powershell"> # Example in Windows PowerShell "hello" -gt "world" # returns false </syntaxhighlight>
<syntaxhighlight lang="lisp"> ;; Example in Common Lisp (string> "art" "painting") ; returns nil (string< "art" "painting") ; returns non nil </syntaxhighlight> <!-- endsection -->
===Concatenation=== {{see also|Concatenation}}
{| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>concatenate(string<sub>1</sub>,string<sub>2</sub>)</code> returns string. |- ! Description | Concatenates (joins) two strings to each other, returning the combined string. Some languages like C have mutable strings, so really the second string is being appended to the first string and the mutated string is returned. |} <!-- table is missing entries for sh --> {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>''string<sub>1</sub>'' ''adjacent_to'' ''string<sub>2</sub>''</code> | Rexx (abutment, equivalent to <code>''string<sub>1</sub>'' || ''string<sub>2</sub>''</code>) |- | <code>''string<sub>1</sub>'' ''whitespace'' ''string<sub>2</sub>''</code> | Rexx (equivalent to <code>''string<sub>1</sub>'' || ' ' || ''string<sub>2</sub>''</code>) |- | <code>''string<sub>1</sub>'' & ''string<sub>2</sub>''</code> |Ada, FreeBASIC, Seed7, BASIC, VB, VB .NET, COBOL (between literals only) |- | <code> strcat(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> | C, C++ (<code>char *</code> only)<ref>modifies ''<code>string<sub>1</sub></code>'', which must have enough space to store the result</ref> |- | <code>''string<sub>1</sub>'' . ''string<sub>2</sub>''</code> |Perl, PHP |- | <code>''string<sub>1</sub>'' + ''string<sub>2</sub>''</code> |ALGOL 68, C++ (STL), C#, Cobra, FreeBASIC, Go, Pascal, Object Pascal (Delphi), Java, JavaScript, Windows PowerShell, Python, Ruby, Rust,<ref>In Rust, the <code>+</code> operator is implemented by the [https://doc.rust-lang.org/stable/std/string/struct.String.html#impl-Add%3C%26%27_%20str%3E <code>Add</code>] trait.</ref> F#, Swift, Turing, VB |- | <code>''string<sub>1</sub>'' ~ ''string<sub>2</sub>''</code> |D, Raku |- | <code>(string-append ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Scheme, ISLISP |- | <code>(concatenate 'string ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Common Lisp |- | <code>(str ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Clojure |- | <code>''string<sub>1</sub>'' <nowiki>||</nowiki> ''string<sub>2</sub>''</code> |Rexx, SQL, PL/I |- | <code>''string<sub>1</sub>'' // ''string<sub>2</sub>''</code> |Fortran |- | <code>''string<sub>1</sub>'' ++ ''string<sub>2</sub>''</code> |Erlang, Haskell |- | <code>''string<sub>1</sub>'' ^ ''string<sub>2</sub>''</code> |OCaml, Standard ML, F# |- | <code>[''string<sub>1</sub>'' stringByAppendingString:''string<sub>2</sub>'']</code> |Objective-C (<code>NSString *</code> only) |- | <code>''string<sub>1</sub>'' .. ''string<sub>2</sub>''</code> |Lua |- | <code>''string<sub>1</sub>'' , ''string<sub>2</sub>''</code> |Smalltalk, APL |- | <code>''string<sub>1</sub>'' ''string<sub>2</sub>''</code> |SNOBOL |- | <code>''string<sub>1</sub>string<sub>2</sub>''</code> |Bash |- | <code>''string<sub>1</sub>'' <> ''string<sub>2</sub>''</code> |Mathematica |- |concat ''string<sub>1</sub> string<sub>2</sub>'' |Tcl |}
<syntaxhighlight lang="pascal"> { Example in Pascal } 'abc' + 'def'; // returns "abcdef" </syntaxhighlight>
<syntaxhighlight lang="csharp"> // Example in C# "abc" + "def"; // returns "abcdef" </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Example in Visual Basic "abc" & "def" ' returns "abcdef" "abc" + "def" ' returns "abcdef" "abc" & Null ' returns "abc" "abc" + Null ' returns Null </syntaxhighlight>
<syntaxhighlight lang="d"> // Example in D "abc" ~ "def"; // returns "abcdef" </syntaxhighlight>
<syntaxhighlight lang="lisp"> ;; Example in common lisp (concatenate 'string "abc " "def " "ghi") ; returns "abc def ghi" </syntaxhighlight>
<syntaxhighlight lang="perl"> # Example in Perl 5 "abc" . "def"; # returns "abcdef" "Perl " . 5; # returns "Perl 5" </syntaxhighlight>
<syntaxhighlight lang="rexx"> /* Example in PL/I */ "abc" || "def" /* returns "abcdef" */ </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku "abc" ~ "def"; # returns "abcdef" "Perl " ~ 6; # returns "Perl 6" </syntaxhighlight>
<syntaxhighlight lang="rexx"> /* Example in Rexx */ "Strike"2 /* returns "Strike2" */ "Strike" 2 /* returns "Strike 2" */ </syntaxhighlight> <!-- endsection -->
===Contains===
{| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>contains(''string'',''substring'')</code> returns boolean |- ! Description | Returns whether ''string'' contains ''substring'' as a substring. This is equivalent to using Find and then detecting that it does not result in the failure condition listed in the third column of the Find section. However, some languages have a simpler way of expressing this test. |- ! Related | Find |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>''string_in_string''(''string'', '''loc int''', ''substring'')</code> | ALGOL 68 |- | <code>''ContainsStr''(''string'', ''substring'')</code> | Object Pascal (Delphi) |- | <code>strstr(''string'', ''substring'') != NULL</code> | C, C++ (<code>char *</code> only) |- | <code>''string''.Contains(''substring'')</code> | C#, VB .NET, Windows PowerShell, F# |- | <code>''string''.contains(''substring'')</code> | Cobra, Java (1.5+), Raku, Rust,<ref>See the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.contains <code>str::contains</code>] method.</ref> C++ (C++23)<ref>See the [https://en.cppreference.com/w/cpp/string/basic_string/contains <code>std::basic_string::contains</code>] method.</ref> |- | <code>''string''.indexOf(''substring'') >= 0</code> |JavaScript |- | <code>strpos(''string'', ''substring'') !== false</code> |PHP |- | <code>str_contains(''string'', ''substring'')</code> |PHP (8+) |- | <code>pos(''string'', ''substring'') <> 0</code> |Seed7 |- | <code>''substring'' in ''string''</code> |Cobra, Python (2.3+) |- | <code>string.find(''string'', ''substring'') ~= nil</code> |Lua |- | <code>''string''.include?(''substring'')</code> |Ruby |- | <code>Data.List.isInfixOf ''substring'' ''string''</code> |Haskell (GHC 6.6+) |- | <code>''string'' includesSubstring: ''substring''</code> |Smalltalk (Squeak, Pharo, Smalltalk/X) |- | <code>String.isSubstring ''substring'' ''string''</code> |Standard ML |- | <code>(search ''substring'' ''string'')</code> |Common Lisp |- | <code>{{codett|2=lisp|(not (null (string-index}} ''substring'' ''string'')))</code> |ISLISP |- | <code>(substring? ''substring'' ''string'')</code> |Clojure |- | <code>! StringFreeQ[''string'', ''substring'']</code> |Mathematica |- | <code>index(''string'', ''substring'', ''startpos'')>0</code> |Fortran, PL/I<ref name="contain1">''startpos'' is IBM extension.</ref> |- | <code>index(''string'', ''substring'', ''occurrence'')>0</code> |Pick Basic |- | <code>strings.Contains(''string'', ''substring'')</code> | Go |- | <code>''string''.find(''substring'') != string::npos</code> | C++ |- | <code>[''string'' containsString:''substring'']</code> |Objective-C (<code>NSString *</code> only, iOS 8+/OS X 10.10+) |- | <code>''string''.rangeOfString(''substring'') != nil</code> |Swift (Foundation) |- | <code>∨/''substring''⍷''string''</code> |APL |}
¢ Example in ALGOL 68 ¢ string in string("e", '''loc int''', "Hello mate"); ¢ returns '''true''' ¢ string in string("z", '''loc int''', "word"); ¢ returns '''false''' ¢
<syntaxhighlight lang="csharp"> // Example In C# "Hello mate".Contains("e"); // returns true "word".Contains("z"); // returns false </syntaxhighlight>
<syntaxhighlight lang="python"> # Example in Python "e" in "Hello mate" # returns true "z" in "word" # returns false </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku "Good morning!".contains('z') # returns False "¡Buenos días!".contains('í'); # returns True </syntaxhighlight>
<syntaxhighlight lang="smalltalk"> " Example in Smalltalk " 'Hello mate' includesSubstring: 'e' " returns true " 'word' includesSubstring: 'z' " returns false " </syntaxhighlight>
===Equality=== <!-- startsection --> Tests if two strings are equal. See also #Compare and #Compare. Doing equality checks via a generic Compare with integer result is not only confusing for the programmer but is often a significantly more expensive operation; this is especially true when using "C-strings".
{| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>''string<sub>1</sub>'' == ''string<sub>2</sub>''</code> |Python, C++ (STL), C#, Cobra, Go, JavaScript (similarity), PHP (similarity), Ruby, Rust,<ref name="Rust compare"/> Erlang, Haskell, Lua, D, Mathematica, Swift |- | <code>''string<sub>1</sub>'' === ''string<sub>2</sub>''</code> |JavaScript, PHP |- | <code>''string<sub>1</sub>'' == ''string<sub>2</sub>''</code><br><code>''string<sub>1</sub>'' .EQ. ''string<sub>2</sub>''</code> |Fortran |- | <code>strcmp(''string<sub>1</sub>'', ''string<sub>2</sub>'') == 0</code> |C |- | <code>(string=? ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Scheme |- | <code>(string= ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Common Lisp, ISLISP |- | <code>''string<sub>1</sub>'' = ''string<sub>2</sub>''</code> |ALGOL 68, Ada, Object Pascal (Delphi), OCaml, Pascal, Rexx, Seed7, Standard ML, BASIC, VB, VB .NET, F#, Smalltalk, PL/I, COBOL |- | <code>test ''string<sub>1</sub>'' = ''string<sub>2</sub>''</code><br><code>[ ''string<sub>1</sub>'' = ''string<sub>2</sub>'' ]</code> |Bourne Shell |- | <code>''string<sub>1</sub>'' eq ''string<sub>2</sub>''</code> |Perl, Raku, Tcl |- | <code>''string<sub>1</sub>''.equals(''string<sub>2</sub>'')</code> |Cobra, Java |- | <code>''string<sub>1</sub>''.Equals(''string<sub>2</sub>'')</code> |C# |- | <code>''string<sub>1</sub>'' -eq ''string<sub>2</sub>''</code><br><code>[string]::Equals(''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |Windows PowerShell |- | <code>[''string<sub>1</sub>'' isEqualToString:''string<sub>2</sub>'']</code><br><code>[''string<sub>1</sub>'' isEqual:''string<sub>2</sub>'']</code> |Objective-C (<code>NSString *</code> only) |- | <code>''string<sub>1</sub>'' ≡ ''string<sub>2</sub>''</code> |APL |- | <code>''string<sub>1</sub>''.eq(''string<sub>2</sub>'')</code> |Rust<ref name="Rust compare" /> |}
<syntaxhighlight lang="csharp"> // Example in C# "hello" == "world" // returns false </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Example in Visual Basic "hello" = "world" ' returns false </syntaxhighlight>
<syntaxhighlight lang="perl"> # Examples in Perl 5 'hello' eq 'world' # returns 0 'hello' eq 'hello' # returns 1 </syntaxhighlight>
<syntaxhighlight lang="raku"> # Examples in Raku 'hello' eq 'world' # returns False 'hello' eq 'hello' # returns True </syntaxhighlight>
<syntaxhighlight lang="ps1"> # Example in Windows PowerShell "hello" -eq "world" # returns false </syntaxhighlight>
<syntaxhighlight lang="apl"> ⍝ Example in APL 'hello' ≡ 'world' ⍝ returns 0 </syntaxhighlight>
<!-- endsection -->
===Find===
{| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>find(''string'',''substring'')</code> returns integer |- ! Description | Returns the position of the start of the first occurrence of ''substring'' in ''string''. If the ''substring'' is not found most of these routines return an invalid index value – -1 where indexes are 0-based, 0 where they are 1-based – or some value to be interpreted as Boolean FALSE. |- ! Related | instrrev |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages !! If not found |- | <code>string in string(substring, pos, ''string[startpos:]'')</code> |ALGOL 68 |returns BOOL: TRUE or FALSE, and position in REF INT pos. |- | <code>InStr(«''startpos'',»''string'',''substring'')</code> |VB (positions start at 1) |returns 0 |- | <code>INSTR$(''string'',''substring'')</code> |BASIC (positions start at 1) |returns 0 |- | <code>index(''string'',''substring'')</code> |AWK |returns 0 |- | <code>index(''string'',''substring''«,''startpos''»)</code> |Perl 5 |returns −1 |- | <code>index(''string'',''substring''«,''startpos''»)</code><br><code>''string''.index(''substring'',«,''startpos''»)</code> |Raku |returns Nil |- | <code>instr(«''startpos'',»''string'',''substring'')</code> |FreeBASIC |returns 0 |- | <code>strpos(''string'',''substring''«,''startpos''»)</code> |PHP |returns FALSE |- | <code>locate(''string'', ''substring'')</code> |Ingres |returns string length + 1 |- | <code>strstr(''string'', ''substring'')</code> |C, C++ (<code>char *</code> only, returns pointer to first character) |returns NULL |- | <code>std.string.indexOf(''string'', ''substring'')</code> |D |returns −1 |- | <code>pos(''string'', ''substring''«, ''startpos''»)</code> |Seed7 |returns 0 |- | <code>strings.Index(''string'', ''substring'')</code> |Go |returns −1 |- | <code>pos(''substring'', ''string'')</code> |Pascal, Object Pascal (Delphi) |returns 0 |- | <code>pos(''substring'', ''string''«,''startpos''»)</code> |Rexx |returns 0 |- | <code>''string''.find(''substring''«,''startpos''»)</code> |C++ (STL) |returns std::string::npos |- | <code>''string''.find(''substring''«,''startpos''«,''endpos''»»)</code> |rowspan=2|Python |returns −1 |- | <code>''string''.index(''substring''«,''startpos''«,''endpos''»»)</code> |raises ValueError |- | <code>''string''.index(''substring''«,''startpos''»)</code> |Ruby |returns nil |- | <code>''string''.indexOf(''substring''«,''startpos''»)</code> |Java, JavaScript |returns −1 |- | <code>''string''.IndexOf(''substring''«,''startpos''«, ''charcount''»»)</code> |VB .NET, C#, Windows PowerShell, F# |returns −1 |- | <code>string:str(''string'', ''substring'')</code> |Erlang |returns 0 |- | <code>(string-contains ''string'' ''substring'')</code> |Scheme (SRFI 13) |returns #f |- | <code>(search ''substring'' ''string'')</code> |Common Lisp |returns NIL |- | <code>(string-index ''substring'' ''string'')</code> |ISLISP |returns <code>nil</code> |- | <code>List.findIndex (List.isPrefixOf ''substring'') (List.tails ''string'')</code> |Haskell (returns only ''index'') |returns Nothing |- | <code>Str.search_forward (Str.regexp_string ''substring'') ''string'' 0</code> |OCaml |raises Not_found |- | <code>Substring.size (#1 (Substring.position ''substring'' (Substring.full ''string'')))</code> |Standard ML |returns string length |- | <code>[''string'' rangeOfString:''substring''].location</code> |Objective-C (<code>NSString *</code> only) |returns NSNotFound |- | <code>string.find(''string'', ''substring'')</code><br><code>(''string''):find(''substring'')</code> |Lua |returns nil |- | <code>''string'' indexOfSubCollection: ''substring'' startingAt: ''startpos'' ifAbsent: ''aBlock''</code><br><code>''string'' findString: ''substring'' startingAt: ''startpos''</code> |Smalltalk (Squeak, Pharo) |evaluate aBlock which is a block closure (or any object understanding value)<br>returns 0 |- | <code>startpos = INDEX(''string'', ''substring'' «,''back''» «, ''kind''»)</code> |Fortran |returns 0 if substring is not in string; returns LEN(string)+1 if substring is empty |- | <code>POSITION(''substring'' IN ''string'')</code> |SQL |returns 0 (positions start at 1) |- | <code>index(''string'', ''substring'', ''startpos'' )</code> |PL/I<ref name="contain1" /> |returns 0 (positions start at 1) |- | <code>index(''string'', ''substring'', ''occurrence'' )</code> |Pick Basic |returns 0 if occurrence of substring is not in string; (positions start at 1) |- | <code>''string''.indexOf(''substring''«,''startpos''«, ''charcount''»»)</code> |Cobra |returns −1 |- | <code>string first ''substring string startpos''</code> |Tcl |returns −1 |- | <code>(''substring''⍷''string'')⍳1</code> |APL |returns 1 + the last position in ''string'' |- | <code>''string''.find(''substring'')</code> |Rust<ref name="Rust find">See the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.find <code>str::find</code>] method.</ref> |returns <code>None</code> |}
'''Examples''' * Common Lisp *: <syntaxhighlight lang="lisp"> (search "e" "Hello mate") ; returns 1 (search "z" "word") ; returns NIL </syntaxhighlight> * C# *: <syntaxhighlight lang="csharp"> "Hello mate".IndexOf("e"); // returns 1 "Hello mate".IndexOf("e", 4); // returns 9 "word".IndexOf("z"); // returns -1 </syntaxhighlight> * Raku *: <syntaxhighlight lang="raku"> "Hello, there!".index('e') # returns 1 "Hello, there!".index('z') # returns Nil </syntaxhighlight> * Scheme *: <syntaxhighlight lang="scheme"> (use-modules (srfi srfi-13)) (string-contains "Hello mate" "e") ; returns 1 (string-contains "word" "z") ; returns #f </syntaxhighlight> * Visual Basic *: <syntaxhighlight lang="vbnet"> ' Examples in InStr("Hello mate", "e") ' returns 2 InStr(5, "Hello mate", "e") ' returns 10 InStr("word", "z") ' returns 0 </syntaxhighlight> * Smalltalk *: <syntaxhighlight lang="smalltalk"> 'Hello mate' indexOfSubCollection:'ate' "returns 8" </syntaxhighlight> *: <syntaxhighlight lang="smalltalk"> 'Hello mate' indexOfSubCollection:'late' "returns 0" </syntaxhighlight> *: <syntaxhighlight lang="smalltalk"> I'Hello mate' indexOfSubCollection:'late' ifAbsent:[ 99 ] "returns 99" </syntaxhighlight> *: <syntaxhighlight lang="smalltalk"> 'Hello mate' indexOfSubCollection:'late' ifAbsent:[ self error ] "raises an exception" </syntaxhighlight>
<!-- endsection -->
===Find character===
{| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>find_character(''string'',''char'')</code> returns integer |- ! Description | Returns the position of the start of the first occurrence of the character ''char'' in ''string''. If the character is not found most of these routines return an invalid index value – -1 where indexes are 0-based, 0 where they are 1-based – or some value to be interpreted as Boolean FALSE. This can be accomplished as a special case of #Find, with a string of one character; but it may be simpler or more efficient in many languages to locate just one character. Also, in many languages, characters and strings are different types, so it is convenient to have such a function. |- | Related | find |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages !! If not found |- | <code>char in string(char, pos, ''string[startpos:]'')</code> |ALGOL 68 |returns {{mono|BOOL}}: {{mono|TRUE}} or {{mono|FALSE}}, and position in {{mono|REF INT pos}}. |- | <code>instr(''string'', any ''char''«,''startpos''»)</code> (char, can contain more them one char, in which case the position of the first appearance of any of them is returned.) |FreeBASIC |returns 0 |- | <code>strchr(''string'',''char'')</code> |C, C++ (<code>char *</code> only, returns pointer to character) |returns {{mono|NULL}} |- | <code>std.string.find(''string'', ''dchar'')</code> |D |returns −1 |- | <code>''string''.find(''char''«,''startpos''»)</code> |C++ (STL) |returns {{mono|std::string::npos}} |- | <code>pos(''string'', ''char''«, ''startpos''»)</code> |Seed7 |returns 0 |- | <code>strings.IndexRune(''string'',''char'')</code> |Go |returns −1 |- | <code>''string''.indexOf(''char''«,''startpos''»)</code> |Java, JavaScript |returns −1 |- | <code>''string''.IndexOf(''char''«,''startpos''«, ''charcount''»»)</code> |VB .NET, C#, Windows PowerShell, F# |returns −1 |- | <code>(position ''char'' ''string'')</code> |Common Lisp |returns {{mono|NIL}} |- | <code>(char-index ''char'' ''string'')</code> |ISLISP |returns {{mono|nil}} |- | <code>List.elemIndex ''char'' ''string''</code> |Haskell (returns <code>Just ''index''</code>) |returns {{mono|Nothing}} |- | <code>String.index ''string'' ''char''</code> |OCaml |raises {{mono|Not_found}} |- | <code>position = SCAN (''string'', ''set'' «, ''back''» «, ''kind''»)</code><br><code>position = VERIFY (''string'', ''set'' «, ''back''» «, ''kind''»){{ref|Fortran find|[a]}}</code> |Fortran |returns zero |- | <code>''string'' indexOf: ''char'' ifAbsent: aBlock</code><br><code>''string'' indexOf: ''char''</code><br><code>''string'' includes: ''char''</code> |Smalltalk |evaluate <code>aBlock</code> which is a <code>BlockClosure</code> (or any object understanding value)<br>returns 0<br>returns <code>true</code> or <code>false</code> |- | <code>index(''string'', ''char'', ''startpos'' )</code> |PL/I<ref name="fc1">''<code>startpos</code>'' is IBM extension.</ref> |returns 0 (positions start at 1) |- |<code>''string''.index(?''char'')</code> |Ruby |returns {{mono|nil}} |- |<code>strpos(''string'',''char'',''startpos'')</code> |PHP |returns {{mono|false}} |- | <code>''string''.indexOf(''char''«,''startpos''«, ''charcount''»»)</code> |Cobra |returns −1 |- | <code>''string''⍳''char''</code> |APL |returns 1 + the last position in ''string'' |- | <code>''string''.find(''substring'')</code> |Rust<ref name="Rust find" /> |returns {{mono|None}} |}
<syntaxhighlight lang="csharp"> // Examples in C# "Hello mate".IndexOf('e'); // returns 1 "word".IndexOf('z') // returns -1 </syntaxhighlight>
<syntaxhighlight lang="lisp"> ; Examples in Common Lisp (position #\e "Hello mate") ; returns 1 (position #\z "word") ; returns NIL </syntaxhighlight> <!-- endsection --> {{note|Fortran find|a}} Given a set of characters, SCAN returns the position of the first character found,<ref>{{cite web|url=http://fortranwiki.org/fortran/show/scan |title=scan in Fortran Wiki |publisher=Fortranwiki.org |date=2009-04-30 |access-date=2013-08-18}}</ref> while VERIFY returns the position of the first character that does not belong to the set.<ref>{{cite web|url=http://fortranwiki.org/fortran/show/verify |title=verify in Fortran Wiki |publisher=Fortranwiki.org |date=2012-05-03 |access-date=2013-08-18}}</ref>
===Format=== {{See also|printf format string}} <!-- startsection --> {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>format(''formatstring'', ''items'')</code> returns string |- ! Description | Returns the formatted string representation of one or more items. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format ! Languages ! Format string syntax |- | <code>associate(''file'', ''string''); putf(''file'', ''$formatstring$'', ''items'')</code> |ALGOL 68 |ALGOL |- | <code>Format(''item'', ''formatstring'')</code> |VB | <code></code> |- | <code>sprintf(''formatstring'', ''items'')</code> |Perl, PHP, Raku, Ruby |C |- | <code>item.fmt(''formatstring'')</code> |Raku |C |- | <code>io_lib:format(''formatstring'', ''items'')</code> |Erlang | <code></code> |- | <code>sprintf(''outputstring'', ''formatstring'', ''items'')</code> |C |C |- | <code>std::format(''formatstring'', ''items'')</code> | C++ (C++20) |Python |- | <code>std.string.format(''formatstring'', ''items'')</code> |D |C |- | <code>Format(''formatstring'', ''items'')</code> |Object Pascal (Delphi) | <code></code> |- | <code>fmt.Sprintf(''formatstring'', ''items'')</code> |Go |C |- | <code>printf ''formatstring'' ''items''</code> |Unix |C |- | <code>''formatstring'' % (''items'')</code> |Python, Ruby |C |- | <code>''formatstring''.format(''items'')</code> |Python |.NET |- |<code>f''formatstring''</code> |Python 3 |- | <code>Printf.sprintf ''formatstring''</code><ref>''<code>formatstring</code>'' must be a fixed literal at compile time for it to have the correct type.</ref><code> ''items''</code> | OCaml, F# |C |- | <code>Text.Printf.printf ''formatstring'' ''items''</code> |Haskell (GHC) |C |- | <code>''formatstring'' printf: ''items''</code> |Smalltalk |C |- | <code>String.format(''formatstring'', ''items'')</code> |Java |C |- | <code>String.Format(''formatstring'', ''items'')</code> |VB .NET, C#, F# |.NET |- | <code>(format ''formatstring'' ''items'')</code> |Scheme (SRFI 28) |Lisp |- | <code>(format nil ''formatstring'' ''items'')</code> |Common Lisp |Lisp |- | <code>(format ''formatstring'' ''items'')</code> |Clojure |Lisp |- | <code>''formatstring'' -f ''items''</code> |Windows PowerShell |.NET |- | <code>[NSString stringWithFormat:''formatstring'', ''items'']</code> |Objective-C (<code>NSString *</code> only) |C |- | <code>String(format:''formatstring'', ''items'')</code> |Swift (Foundation) |C |- | <code>string.format(''formatstring'', ''items'')</code><br><code>(''formatstring''):format(''items'')</code> |Lua |C |- | <code>WRITE (''outputstring'', ''formatstring'') ''items''</code> |Fortran |Fortran |- | <code>put string(''string'') edit(''items'')(''format'')</code> |PL/I |PL/I (similar to Fortran) |- | <code>String.format(''formatstring'', ''items'')</code> |Cobra |.NET |- | <code>format ''formatstring items''</code> |Tcl |C |- | <code>''formatnumbers'' ⍕ ''items''</code><br><code>''formatstring'' ⎕FMT ''items''</code> |APL |APL |- | <code>format!(''formatstring'', ''items'')</code> | Rust<ref>See [https://doc.rust-lang.org/stable/std/macro.format.html <code>std::format</code>], which is imported by the Rust [https://doc.rust-lang.org/stable/std/prelude/ prelude] so that it can be used under the name <code>format</code>.</ref> | Python |}
<syntaxhighlight lang="csharp"> // Example in C# String.Format("My {0} costs {1:C2}", "pen", 19.99); // returns "My pen costs $19.99" </syntaxhighlight>
<syntaxhighlight lang="delphi"> // Example in Object Pascal (Delphi) Format('My %s costs $%2f', ['pen', 19.99]); // returns "My pen costs $19.99" </syntaxhighlight>
<syntaxhighlight lang="java"> // Example in Java String.format("My %s costs $%2f", "pen", 19.99); // returns "My pen costs $19.99" </syntaxhighlight>
<syntaxhighlight lang="raku"> # Examples in Raku sprintf "My %s costs \$%.2f", "pen", 19.99; # returns "My pen costs $19.99" 1.fmt("%04d"); # returns "0001" </syntaxhighlight>
<syntaxhighlight lang="python"> # 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" </syntaxhighlight> <syntaxhighlight lang="python3"> #Example in Python 3.6+ pen = "pen" f"My {pen} costs {19.99}" #returns "My pen costs 19.99" </syntaxhighlight>
<syntaxhighlight lang="scheme"> ; Example in Scheme (format "My ~a costs $~1,2F" "pen" 19.99) ; returns "My pen costs $19.99" </syntaxhighlight>
<syntaxhighlight lang="rexx"> /* 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" */ </syntaxhighlight> <!-- endsection -->
===Inequality=== <!-- startsection --> Tests if two strings are not equal. See also #Equality. {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>''string<sub>1</sub>'' '''ne''' ''string<sub>2</sub>''</code><br><code>''string<sub>1</sub>'' NE ''string<sub>2</sub>''</code> |ALGOL 68 – The operator "'''ne'''" occurs in '''bold''' type-font. |- | <code>''string<sub>1</sub>'' /= ''string<sub>2</sub>''</code> |ALGOL 68, Ada, Erlang, Fortran, Haskell |- | <code>''string<sub>1</sub>'' <> ''string<sub>2</sub>''</code> |BASIC, VB, VB .NET, Pascal, Object Pascal (Delphi), OCaml, PHP, Seed7, Standard ML, F#, COBOL, Cobra, Python 2 (deprecated) |- | <code>''string<sub>1</sub>'' # ''string<sub>2</sub>''</code> |BASIC (some implementations) |- | <code>''string<sub>1</sub>'' ne ''string<sub>2</sub>''</code> |Perl, Raku |- | <code>(string<> ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Scheme (SRFI 13) |- | <code>(string/= ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Common Lisp |- | <code>(string/= ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |ISLISP |- | <code>(not= ''string<sub>1</sub>'' ''string<sub>2</sub>'')</code> |Clojure |- | <code>''string<sub>1</sub>'' != ''string<sub>2</sub>''</code> |C++ (STL), C#, Go, JavaScript (not similar), PHP (not similar), Python, Ruby, Rust,<ref name="Rust compare" /> Swift, D, Mathematica |- | <code>''string<sub>1</sub>'' !== ''string<sub>2</sub>''</code> |JavaScript, PHP |- | <code>''string<sub>1</sub>'' \= ''string<sub>2</sub>''</code> |Rexx |- | <code>''string<sub>1</sub>'' ¬= ''string<sub>2</sub>''</code> |PL/I |- | <code>test ''string<sub>1</sub>'' != ''string<sub>2</sub>''</code><br><code>[ ''string<sub>1</sub>'' != ''string<sub>2</sub>'' ]</code> |Bourne Shell |- | <code>''string<sub>1</sub>'' -ne ''string<sub>2</sub>''</code><br><code>{{codett|-not [string]::Equals(|ps1}}''string<sub>1</sub>'', ''string<sub>2</sub>'')</code> |Windows PowerShell |- | <code>''string<sub>1</sub>'' ~= ''string<sub>2</sub>''</code> |Lua, Smalltalk |- | <code>''string<sub>1</sub>'' ≢ ''string<sub>2</sub>''</code> |APL |- | <code>''string<sub>1</sub>''.ne(''string<sub>2</sub>'')</code> | Rust<ref name="Rust compare" /> |}
<syntaxhighlight lang="csharp"> // Example in C# "hello" != "world" // returns true </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Example in Visual Basic "hello" <> "world" ' returns true </syntaxhighlight>
<syntaxhighlight lang="clojure"> ;; Example in Clojure (not= "hello" "world") ; ⇒ true </syntaxhighlight>
<syntaxhighlight lang="perl"> # Example in Perl 5 'hello' ne 'world' # returns 1 </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku 'hello' ne 'world' # returns True </syntaxhighlight>
<syntaxhighlight lang="powershell"> # Example in Windows PowerShell "hello" -ne "world" # returns true </syntaxhighlight> <!-- endsection -->
===index=== ''see'' #Find
===indexof=== ''see'' #Find
===instr=== ''see'' #Find
===instrrev=== ''see'' #rfind
===join=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code> join(''separator'', ''list_of_strings'')</code> returns a list of strings joined with a separator |- ! Description | Joins the list of strings into a new string, with the separator string between each of the substrings. Opposite of ''split''. |- | Related | sprintf |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>std.string.join(''array_of_strings'', ''separator'')</code> |D |- | <code>string:join(''list_of_strings'', ''separator'')</code> |Erlang |- | <code>join(''separator'', ''list_of_strings'')</code> |Perl, PHP, Raku |- | <code>implode(''separator'', ''array_of_strings'')</code> |PHP |- | <code>''separator''.join(''sequence_of_strings'')</code> |Python, Swift 1.x |- | <code>''array_of_strings''.join(''separator'')</code> |Ruby, JavaScript, Raku, Rust<ref>See the [https://doc.rust-lang.org/stable/std/primitive.slice.html#method.join <code>slice::join</code>] method.</ref> |- | <code>(string-join ''array_of_strings'' ''separator'')</code> |Scheme (SRFI 13) |- | <code>(format nil "~{~a~^''separator''~}" ''array_of_strings'')</code> |Common Lisp |- | <code>(clojure.string/join ''separator'' ''list_of_strings'')</code><br><code>(apply str (interpose ''separator'' ''list_of_strings''))</code> |Clojure |- | <code>strings.Join(''array_of_strings'', ''separator'')</code> |Go |- | <code>join(''array_of_strings'', ''separator'')</code> |Seed7 |- | <code>String.concat ''separator'' ''list_of_strings''</code> |OCaml |- | <code>String.concatWith ''separator'' ''list_of_strings''</code> |Standard ML |- | <code>Data.List.intercalate ''separator'' ''list_of_strings''</code> |Haskell (GHC 6.8+) |- | <code>Join(''array_of_strings'', ''separator'')</code> |VB |- | <code>String.Join(''separator'', ''array_of_strings'')</code> |VB .NET, C#, F# |- | <code>String.join(''separator'', ''array_of_strings'')</code> |Java 8+ |- | <code>&{$OFS=''$separator''; "''$array_of_strings''"}</code><br><code>''array_of_strings'' -join ''separator''</code> |Windows PowerShell |- | <code>[''array_of_strings'' componentsJoinedByString:''separator'']</code> |Objective-C (<code>NSString *</code> only) |- | <code>table.concat(''table_of_strings'', ''separator'')</code> |Lua |- | <code>{{codett|<nowiki>{|String streamContents: [ :stream |</nowiki>|smalltalk}} ''collectionOfAnything'' asStringOn: stream delimiter: ''separator'' <nowiki>]</nowiki></code><br><code>''collectionOfAnything'' joinUsing: ''separator''</code> |Smalltalk (Squeak, Pharo) |- | <code>''array_of_strings''.join(''separator''«, ''final_separator''»)</code> |Cobra |- | <code>''sequence_of_strings''.joinWithSeparator(''separator'')</code> |Swift 2.x |- | <code>1↓∊''separator'',¨''list_of_strings''</code> |APL |}
<syntaxhighlight lang="csharp"> // Example in C# String.Join("-", {"a", "b", "c"}) // "a-b-c" </syntaxhighlight>
<syntaxhighlight lang="smalltalk"> " Example in Smalltalk " #('a' 'b' 'c') joinUsing: '-' " 'a-b-c' " </syntaxhighlight>
<syntaxhighlight lang="perl"> # Example in Perl 5 join( '-', ('a', 'b', 'c')); # 'a-b-c' </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku <a b c>.join('-'); # 'a-b-c' </syntaxhighlight>
<syntaxhighlight lang="python"> # Example in Python "-".join(["a", "b", "c"]) # 'a-b-c' </syntaxhighlight>
<syntaxhighlight lang="ruby"> # Example in Ruby ["a", "b", "c"].join("-") # 'a-b-c' </syntaxhighlight>
<syntaxhighlight lang="scheme"> ; Example in Scheme (use-modules (srfi srfi-13)) (string-join '("a" "b" "c") "-") ; "a-b-c" </syntaxhighlight> <!-- endsection -->
===lastindexof=== ''see'' #rfind
===left=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>left(''string'',''n'')</code> returns string |- ! Description | Returns the left ''n'' part of a string. If ''n'' is greater than the length of the string then most implementations return the whole string (exceptions exist – see code examples). For variable-length encodings such as UTF-8, UTF-16 or Shift-JIS, it can be necessary to remove string positions at the end, to avoid invalid strings. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- |<code>{{codett|string (string'First .. string'First +|ada}} ''n'' - 1)</code> |Ada |- | <code>substr(''string'', 0, ''n'')</code> |AWK (changes string), Perl, PHP, Raku |- | <code>LEFT$(''string'',''n'')</code> |BASIC, VB |- | <code>left(''string'',''n'')</code> ||VB, FreeBASIC, Ingres, Pick Basic |- | <code>strncpy(''string2'', ''string'', ''n'')</code> |C standard library |- | <code>''string''.substr(0,''n'')</code> |C++ (STL), Raku |- | <code>[''string'' substringToIndex:''n'']</code> |Objective-C (<code>NSString *</code> only) |- | <code>{{codett|(apply str (take|clojure}} ''n'' ''string''))</code> |Clojure |- | <code>''string''[0 .. ''n'']</code> |D<ref>if n is larger than the length of the string, then in Debug mode ArrayRangeException is thrown, in Release mode, the behaviour is unspecified.</ref> |- | <code>string:substr(''string'', ''start'', ''length'')</code> |Erlang |- | <code>(subseq ''string'' 0 ''n'')</code> |Common Lisp |- | <code>''string''[:''n'']</code> |Cobra, Go, Python |- | <code>left(''string'',''n'' «,''padchar''»)</code> |Rexx, Erlang |- | <code>''string''[0, ''n'']</code><br><code>''string''[0..''n'' - 1]</code> |Ruby |- | <code>''string''[1, ''n'']</code> |Pick Basic |- | <code>''string''[ .. ''n'']</code> |Seed7 |- | <code>''string''.Substring(0,''n'')</code> |VB .NET, C#, Windows PowerShell, F# |- | <code>leftstr(''string'', ''n'')</code> |Pascal, Object Pascal (Delphi) |- |<code>''copy'' (''string'',1,''n'')</code> |Turbo Pascal |- | <code>''string''.substring(0,''n'')</code> |Java,<ref>if n is larger than the length of the string, Java will throw an IndexOutOfBoundsException</ref> JavaScript |- | <code>(string-take ''string'' ''n'')</code> |Scheme (SRFI 13) |- | <code>take ''n'' ''string''</code> |Haskell |- | <code>String.extract (''string'', ''n'', NONE)</code> |Standard ML |- | <code>String.sub ''string'' 0 ''n''</code> |OCaml<ref name="ReferenceA">if n is larger than length of string, raises Invalid_argument</ref> |- | <code>''string''.[..''n'']</code> |F# |- | <code>string.sub(''string'', 1, ''n'')</code><br><code>(''string''):sub(1, ''n'')</code> |Lua |- | <code>''string'' first: ''n''</code> |Smalltalk (Squeak, Pharo) |- | <code>''string''(:''n'')</code> |Fortran |- | <code>StringTake[''string'', ''n'']</code> |Mathematica<ref name="ReferenceB">if n is larger than length of string, throw the message "StringTake::take:"</ref> |- |<code>''string'' («FUNCTION» LENGTH(''string'') - ''n'':''n'')</code> |COBOL |- |<code>''string''.substring(0, ''n'')</code> |Cobra |- |<code>''n''↑''string''.</code> |APL |- | <code>''string''[0..n]</code><br><code>''string''[..n]</code><br><code>''string''.get(0..n)</code><br><code>''string''.get(..n)</code> | Rust<ref name="Rust indexing">In 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 invalid UTF-8. A <code>&str</code> (string reference) can be [https://doc.rust-lang.org/stable/std/primitive.str.html#impl-Index%3CI%3E indexed] by various types of ranges, including [https://doc.rust-lang.org/stable/std/slice/trait.SliceIndex.html#impl-SliceIndex%3Cstr%3E <code>Range</code>] (<code>0..n</code>), [https://doc.rust-lang.org/stable/std/slice/trait.SliceIndex.html#impl-SliceIndex%3Cstr%3E-1 <code>RangeFrom</code>] (<code>n..</code>), and [https://doc.rust-lang.org/stable/std/slice/trait.SliceIndex.html#impl-SliceIndex%3Cstr%3E-4 <code>RangeTo</code>] (<code>..n</code>) because they all implement the [https://doc.rust-lang.org/stable/std/slice/trait.SliceIndex.html <code>SliceIndex</code>] trait with <code>str</code> being the type being indexed.
The [https://doc.rust-lang.org/stable/std/primitive.str.html#method.get <code>str::get</code>] method is the non-panicking way to index. It returns <code>None</code> in the cases in which indexing would panic.</ref> |}
<syntaxhighlight lang="raku"> # Example in Raku "Hello, there!".substr(0, 6); # returns "Hello," </syntaxhighlight>
<syntaxhighlight lang="rexx"> /* Examples in Rexx */ left("abcde", 3) /* returns "abc" */ left("abcde", 8) /* returns "abcde " */ left("abcde", 8, "*") /* returns "abcde***" */ </syntaxhighlight>
<syntaxhighlight lang="scheme"> ; Examples in Scheme (use-modules (srfi srfi-13)) (string-take "abcde", 3) ; returns "abc" (string-take "abcde", 8) ; error </syntaxhighlight>
<syntaxhighlight lang="vbscript"> ' Examples in Visual Basic Left("sandroguidi", 3) ' returns "san" Left("sandroguidi", 100) ' returns "sandroguidi" </syntaxhighlight>
<!-- endsection -->
===len=== ''see'' #length
<!-- endsection -->
===length=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>length(''string'')</code> returns an integer number |- ! Description | Returns the length of a string (not counting the null terminator or any other of the string's internal structural information). An empty string returns a length of 0. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Returns !! Languages |- |<code>string'Length</code> | <code></code> |Ada |- |<code>UPB string</code> | <code></code> |ALGOL 68 |- |<code>echo "${#''string_param''}"</code> | <code></code> |Bash |- | <code>length(''string'')</code> | <code></code> |Ingres, Perl 5, Pascal, Object Pascal (Delphi), Rexx, Seed7, SQL, PL/I |- | <code>len(''string'')</code> | <code></code> |BASIC, FreeBASIC, Python, Go, Pick Basic |- | <code>length(''string''), string:len(''string'')</code> | <code></code> |Erlang |- | <code>Len(''string'')</code> | <code></code> |VB, Pick Basic |- | <code>''string''.Length</code> |Number of UTF-16 code units |VB .NET, C#, Windows PowerShell, F# |- | <code>chars(''string'')</code><br><code>''string''.chars</code> |Number of graphemes (NFG) |Raku |- | <code>codes(''string'')</code><br><code>''string''.codes</code> |Number of Unicode code points |Raku |- | <code>''string''.size OR ''string''.length</code> |Number of bytes<ref>Ruby lacks Unicode support</ref> |Ruby |- | <code>strlen(''string'')</code> |Number of bytes |C, PHP |- | <code>''string''.length()</code> | <code></code> |C++ (STL) |- | <code>''string''.length</code> | <code></code> |Cobra, D, JavaScript |- | <code>''string''.length()</code> |Number of UTF-16 code units |Java |- | <code>(string-length ''string'')</code> | <code></code> |Scheme |- | <code>(length ''string'')</code> | <code></code> |Common Lisp, ISLISP |- | <code>(count ''string'')</code> | <code></code> |Clojure |- | <code>String.length ''string''</code> | <code></code> |OCaml |- | <code>size ''string''</code> | <code></code> |Standard ML |- | <code>length ''string''</code> |Number of Unicode code points |Haskell |- | <code>''string''.length</code> | Number of UTF-16 code units |Objective-C (<code>NSString *</code> only) |- | <code>''string''.characters.count</code> | Number of characters |Swift (2.x) |- | <code>count(''string'')</code> | Number of characters |Swift (1.2) |- | <code>countElements(''string'')</code> | Number of characters |Swift (1.0–1.1) |- | <code>string.len(''string'')</code><br><code>(''string''):len()</code><br><code>#''string''</code> | <code></code> |Lua |- | <code>''string'' size</code> | <code></code> |Smalltalk |- | <code>LEN(''string'')</code><br><code>LEN_TRIM(''string'')</code> | <code></code> |Fortran |- | <code>StringLength[''string'']</code> | <code></code> |Mathematica |- |<code>«FUNCTION» LENGTH(''string'')</code> or <code>«FUNCTION» BYTE-LENGTH(''string'')</code> | number of characters and number of bytes, respectively | COBOL |- |<code>string length ''string''</code> |a decimal string giving the number of characters |Tcl |- |<code>≢ ''string''</code> | |APL |- | <code>''string''.len()</code> | Number of bytes | Rust<ref>See the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.len <code>str::len</code>] method.</ref> |- | <code>''string''.chars().count()</code> | Number of Unicode code points | Rust<ref>In Rust, the [https://doc.rust-lang.org/std/primitive.str.html#method.chars <code>str::chars</code>] method iterates over code points and the [https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.count <code>std::iter::Iterator::count</code>] method on iterators consumes the iterator and returns the total number of elements in the iterator.</ref> |}
<syntaxhighlight lang="csharp"> // Examples in C# "hello".Length; // returns 5 "".Length; // returns 0 </syntaxhighlight>
<syntaxhighlight lang="erlang"> # Examples in Erlang string:len("hello"). % returns 5 string:len(""). % returns 0 </syntaxhighlight>
<syntaxhighlight lang="perl"> # Examples in Perl 5 length("hello"); # returns 5 length(""); # returns 0 </syntaxhighlight>
<syntaxhighlight lang="raku"> # Examples in Raku "".chars; chars ""; # both return 0 "".codes; codes ""; # both return 0 </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Examples in Visual Basic Len("hello") ' returns 5 Len("") ' returns 0 </syntaxhighlight>
<syntaxhighlight lang="objc"> //Examples in Objective-C [@"hello" Length] //returns 5 [@"" Length] //returns 0 </syntaxhighlight>
<syntaxhighlight lang="lua"> -- Examples in Lua ("hello"):len() -- returns 5 #"" -- returns 0 </syntaxhighlight> <!-- endsection -->
===locate===
''see'' #Find
<!-- endsection -->
===Lowercase=== <!-- startsection --> {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>lowercase(''string'')</code> returns string |- ! Description | Returns the string in lower case. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>LCase(''string'')</code> |VB |- | <code>lcase(''string'')</code> |FreeBASIC |- | <code>lc(''string'')</code> |Perl, Raku |- | <code>''string''.lc</code> |Raku |- |<code>tolower(''char'')</code> |C<ref>operates on one character</ref> |- | <code>std.string.toLower(''string'')</code> |D |- | <code>transform(''string''.begin(), ''string''.end(), ''result''.begin(), ::tolower)</code><ref name="cpptransform">The <code>transform</code> function exists in the <code>std::</code> namespace. You must include the <code><algorithm></code> header file to use it. The <code>tolower</code> and <code>toupper</code> functions are in the global namespace, obtained by the <code><ctype.h></code> header file. The <code>std::tolower</code> and <code>std::toupper</code> names are overloaded and cannot be passed to <code>std::transform</code> without a cast to resolve a function overloading ambiguity, e.g. <code>std::transform(''string''.begin(), ''string''.end(), ''result''.begin(), (int (*)(int))std::tolower);</code></ref> | C++<ref><code>std::string</code> only, result is stored in string ''<code>result</code>'' which is at least as long as ''<code>string</code>'', and may or may not be ''<code>string</code>'' itself</ref> |- | <code>lowercase(''string'')</code> |Object Pascal (Delphi) |- | <code>strtolower(''string'')</code> |PHP |- | <code>lower(''string'')</code> |Seed7 |- |<code>${''string_param'',,}</code> |Bash |- |<code>echo "string" <nowiki>|</nowiki> tr 'A-Z' 'a-z'</code> |Unix |- | <code>''string''.lower()</code> |Python |- | <code>downcase(''string'')</code> |Pick Basic |- | <code>''string''.downcase</code> |Ruby<ref name="ReferenceC">only ASCII characters as Ruby lacks Unicode support</ref> |- | <code>strings.ToLower(''string'')</code> |Go |- | <code>(string-downcase ''string'')</code> |Scheme (R6RS), Common Lisp |- | <code>(lower-case ''string'')</code> |Clojure |- | <code>String.lowercase ''string''</code> |OCaml |- | <code>String.map Char.toLower ''string''</code> |Standard ML |- | <code>map Char.toLower ''string''</code> |Haskell |- | <code>''string''.toLowerCase()</code> |Java, JavaScript |- | <code>to_lower(''string'')</code> |Erlang |- | <code>''string''.ToLower()</code> |VB .NET, C#, Windows PowerShell, F# |- | <code>''string''.lowercaseString</code> |Objective-C (<code>NSString *</code> only), Swift (Foundation) |- | <code>string.lower(''string'')</code><br><code>(''string''):lower()</code> |Lua |- | <code>''string'' asLowercase</code> |Smalltalk |- | <code>LOWER(''string'')</code> |SQL |- | <code>lowercase(''string'')</code> |PL/I<ref name="lower1" /> |- | <code>ToLowerCase[''string'']</code> |Mathematica |- | <code>«FUNCTION» LOWER-CASE(''string'')</code> |COBOL |- | <code>''string''.toLower</code> |Cobra |- | <code>string tolower ''string''</code> |Tcl |- | <code>''string''.to_lowercase()</code> | Rust<ref>See the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.to_lowercase <code>str::to_lowercase</code>] method.</ref> |}
<syntaxhighlight lang="csharp"> // Example in C# "Wiki means fast?".ToLower(); // "wiki means fast?" </syntaxhighlight>
<syntaxhighlight lang="scheme"> ; Example in Scheme (use-modules (srfi srfi-13)) (string-downcase "Wiki means fast?") ; "wiki means fast?" </syntaxhighlight>
<syntaxhighlight lang="c"> /* Example in C */ #include <ctype.h> #include <stdio.h>
int main(void) { char s[] = "Wiki means fast?"; for (int i = 0; i < sizeof(s) - 1; ++i) { // transform characters in place, one by one s[i] = tolower(s[i]); } printf(string); // "wiki means fast?" return 0; } </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku "Wiki means fast?".lc; # "wiki means fast?" </syntaxhighlight>
<!-- endsection -->
===mid=== ''see'' #substring
<!-- endsection -->
===partition=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <string>.partition(''separator'') returns the sub-string before the separator; the separator; then the sub-string after the separator. |- ! Description | Splits the given string by the separator and returns the three substrings that together make the original. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages !! Comments |- | <code>''string''.partition(''separator'')</code> |Python, Ruby(1.9+) | |- | <code>lists:partition(''pred'', ''string'')</code> |Erlang | |- | <code>split /(''separator'')/, ''string'', 2</code> |Perl 5 | |- | <code>split ''separator'', ''string'', 2</code><br><code>''string''.split( ''separator'', 2 )</code> |Raku |Separator does not have to be a regular expression |}
<syntaxhighlight lang="python"> # 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', "", "") </syntaxhighlight>
<syntaxhighlight lang="perl"> # Examples in Perl 5 / Raku split /(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'); </syntaxhighlight>
<!-- endsection -->
===replace=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>replace(''string'', ''find'', ''replace'')</code> returns string |- ! Description | Returns a string with ''find'' occurrences changed to ''replace''. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>changestr(''find'', ''string'', ''replace'')</code> |Rexx |- | <code>std.string.replace(''string'', ''find'', ''replace'')</code> |D |- | <code>Replace(''string'', ''find'', ''replace'')</code> |VB |- | <code>replace(''string'', ''find'', ''replace'')</code> |Seed7 |- | <code>change(''string'', ''find'', ''replace'')</code> |Pick Basic |- | <code>''string''.Replace(''find'', ''replace'')</code> | C#, F#, VB .NET |- | <code>str_replace(''find'', ''replace'', ''string'')</code> |PHP |- | <code>re:replace(''string'', ''find'', ''replace'', «{return, list}»)</code> |Erlang |- | <code>''string''.replace(''find'', ''replace'')</code> |Cobra, Java (1.5+), Python, Rust<ref>See the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.replace <code>str::replace</code>] method.</ref> |- | <code>''string''.replaceAll(''find_regex'', ''replace'')<ref name="regex" /></code> |Java |- | <code>''string''.gsub(''find'', ''replace'')</code> |Ruby |- | <code>''string'' =~ s/''find_regex''/''replace''/g<ref name="regex">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.</ref></code> |Perl 5 |- | <code>''string''.subst(''find'', ''replace'', :g)</code> |Raku |- | <code>''string''.replace(''find'', ''replace'', "g") <ref>third parameter is non-standard</ref></code><br><code>''string''.replace(/''find_regex''/g, ''replace'')<ref name="regex" /></code> |JavaScript |- | <code>echo "''string''" <nowiki>|</nowiki> sed 's/''find_regex''/''replace''/g'<ref name="regex" /></code> |Unix |- | <code>${''string_param''//''find_pattern''/''replace''}</code> |Bash |- | <code>''string''.replace(''find'', ''replace'')</code><br><code>''string'' -replace ''find_regex'', ''replace''<ref name="regex" /></code> |Windows PowerShell |- | <code>Str.global_replace (Str.regexp_string ''find'') ''replace'' ''string''</code> |OCaml |- | <code>[''string'' stringByReplacingOccurrencesOfString:''find'' withString:''replace'']</code> |Objective-C (<code>NSString *</code> only) |- | <code>''string''.stringByReplacingOccurrencesOfString(''find'', withString:''replace'')</code> |Swift (Foundation) |- | <code>string.gsub(''string'', ''find'', ''replace'')</code><br><code>(''string''):gsub(''find'', ''replace'')</code> |Lua |- | <code>''string'' copyReplaceAll: ''find'' with: ''replace''</code> |Smalltalk (Squeak, Pharo) |- | <code>string map {''find'' ''replace''} ''string''</code> |Tcl |- | <code>StringReplace[''string'', ''find'' -> ''replace'']</code> |Mathematica |- | <code>strings.Replace(''string'', ''find'', ''replace'', -1)</code> | Go |- | <code>INSPECT ''string'' REPLACING ALL/LEADING/FIRST ''find'' BY ''replace''</code> | COBOL |- | <code>''find_regex'' ⎕R ''replace_regex'' ⊢ ''string''</code> | APL |}
<syntaxhighlight lang="csharp"> // Examples in C# "effffff".Replace("f", "jump"); // returns "ejumpjumpjumpjumpjumpjump" "blah".Replace("z", "y"); // returns "blah" </syntaxhighlight>
<syntaxhighlight lang="java"> // Examples in Java "effffff".replace("f", "jump"); // returns "ejumpjumpjumpjumpjumpjump" "effffff".replaceAll("f*", "jump"); // returns "ejump" </syntaxhighlight>
<syntaxhighlight lang="raku"> // Examples in Raku "effffff".subst("f", "jump", :g); # returns "ejumpjumpjumpjumpjumpjump" "blah".subst("z", "y", :g); # returns "blah" </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Examples in Visual Basic Replace("effffff", "f", "jump") ' returns "ejumpjumpjumpjumpjumpjump" Replace("blah", "z", "y") ' returns "blah" </syntaxhighlight>
<syntaxhighlight lang="powershell"> # Examples in Windows PowerShell "effffff" -replace "f", "jump" # returns "ejumpjumpjumpjumpjumpjump" "effffff" -replace "f*", "jump" # returns "ejump" </syntaxhighlight> <!-- endsection -->
===reverse=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>reverse(''string'')</code> |- ! Description | Reverses the order of the characters in the string. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>reverse ''string''</code> |Perl 5, Haskell |- | <code>flip ''string''</code><br><code>''string''.flip</code> |Raku<!-- reverses graphemes --> |- | <code>lists:reverse(''string'')</code> |Erlang |- | <code>strrev(''string'')</code> |PHP |- | <code>''string''[::-1]</code> |Python |- | <code>(string-reverse ''string'')</code> |Scheme (SRFI 13) |- | <code>(reverse ''string'')</code> |Common Lisp |- | <code>''string''.reverse</code> |Ruby, D (modifies string) |- | <code>new StringBuilder(''string'').reverse().toString()</code> |Java |- | <code>std::reverse(''string''.begin(), ''string''.end());</code> |C++ (<code>std::string</code> only, modifies string) |- | <code>StrReverse(''string'')</code> |VB |- | <code>''string''.Reverse()</code> |VB .NET, C# |- | <code>implode (rev (explode ''string''))</code> |Standard ML |- | <code>''string''{{codett|2=javascript|.split("").reverse().join("")}}</code> |JavaScript |- | <code>string.reverse(''string'')</code><br><code>(''string''):reverse()</code> |Lua |- | <code>''string'' reverse</code> |Smalltalk |- | <code>StringReverse[''string'']</code> |Mathematica |- |<code>reverse(''string'')</code> |PL/I |- |<code>{{codett|2=cobolfree|«FUNCTION» REVERSE(}}''string'')</code> |COBOL |- |<code>''string''.toCharArray.toList.reversed.join()</code> |Cobra |- | <code>String(''string''.characters.reverse())</code> |Swift (2.x) |- | <code>String(reverse(''string''))</code> |Swift (1.2) |- | <code>string reverse ''string''</code> |Tcl |- | <code>⌽''string''</code> |APL |- | <code>''string''{{codett|2=rust|.chars().rev().collect::<String>()}}</code> | Rust<ref>In Rust, the [https://doc.rust-lang.org/std/primitive.str.html#method.chars <code>str::chars</code>] method iterates over code points, the [https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.rev <code>std::iter::Iterator::rev</code>] method on reversible iterators ([https://doc.rust-lang.org/stable/std/iter/trait.DoubleEndedIterator.html <code>std::iter::DoubleEndedIterator</code>]) creates a reversed iterator, and the [https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect <code>std::iter::Iterator::collect</code>] method consumes the iterator and creates a collection (which here is specified as a [https://doc.rust-lang.org/stable/std/string/struct.String.html <code>String</code>] with the turbofish syntax) from the iterator's elements.</ref> |- | <code>echo ''string'' <nowiki>|</nowiki> rev</code> | Unix |}
<syntaxhighlight lang="smalltalk"> " Example in Smalltalk " 'hello' reversed " returns 'olleh' " </syntaxhighlight>
<syntaxhighlight lang="perl"> # Example in Perl 5 reverse "hello" # returns "olleh" </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku "hello".flip # returns "olleh" </syntaxhighlight>
<syntaxhighlight lang="python"> # Example in Python "hello"[::-1] # returns "olleh" </syntaxhighlight>
<syntaxhighlight lang="scheme"> ; Example in Scheme (use-modules (srfi srfi-13)) (string-reverse "hello") ; returns "olleh" </syntaxhighlight> <!-- endsection -->
===rfind=== <!-- startsection --> {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>rfind(''string'',''substring'')</code> returns integer |- ! Description | Returns the position of the start of the last occurrence of ''substring'' in ''string''. If the ''substring'' is not found most of these routines return an invalid index value – -1 where indexes are 0-based, 0 where they are 1-based – or some value to be interpreted as Boolean FALSE. |- | Related | instr |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages !! If not found |- | <code>InStrRev(«''startpos'',» ''string'',''substring'')</code> |VB |returns 0 |- | <code>instrrev(«''startpos'',» ''string'',''substring'')</code> |FreeBASIC |returns 0 |- | <code>rindex(''string'',''substring''«,''startpos''»)</code> |Perl 5 |returns −1 |- | <code>rindex(''string'',''substring''«,''startpos''»)</code><br><code>''string''.rindex(''substring''«,''startpos''»)</code> |Raku |returns {{mono|Nil}} |- | <code>strrpos(''string'',''substring''«,''startpos''»)</code> |PHP |returns {{mono|FALSE}} |- | <code>''string''.rfind(''substring''«,''startpos''»)</code> |C++ (STL) |returns {{mono|std::string::npos}} |- | <code>std.string.rfind(''string'', ''substring'')</code> |D |returns −1 |- | <code>''string''.rfind(''substring''«,''startpos''«, ''endpos''»»)</code> |rowspan=2|Python |returns −1 |- |<code>''string''.rindex(''substring''«,''startpos''«, ''endpos''»»)</code> |raises {{mono|ValueError}} |- |<code>rpos(''string'', ''substring''«,''startpos''»)</code> |Seed7 |returns 0 |- |<code>''string''.rindex(''substring''«,''startpos''»)</code> |Ruby |returns {{mono|nil}} |- | <code>strings.LastIndex(''string'', ''substring'')</code> |Go |returns −1 |- | <code>''string''.lastIndexOf(''substring''«,''startpos''»)</code> |Java, JavaScript |returns −1 |- | <code>''string''.LastIndexOf(''substring''«,''startpos''«, ''charcount''»»)</code> |VB .NET, C#, Windows PowerShell, F# |returns −1 |- | <code>(search ''substring'' ''string'' :from-end t)</code> |Common Lisp |returns {{mono|NIL}} |- | <code>[''string'' rangeOfString:''substring'' options:NSBackwardsSearch].location</code> |Objective-C (<code>NSString *</code> only) |returns {{mono|NSNotFound}} |- | <code>Str.search_backward (Str.regexp_string ''substring'') ''string'' (Str.length ''string'' - 1)</code> |OCaml |raises {{mono|Not_found}} |- | <code>string.match(''string'', '.*()'..''substring'')</code><br><code>''string''{{codett|2=lua|1=:match('.*()'..}}''substring'')</code> |Lua |returns {{mono|nil}} |- | <code>Ada.Strings.Unbounded.Index(Source => ''string'', Pattern => ''substring'', Going => Ada.Strings.Backward)</code> |Ada |returns 0 |- |<code>''string''.lastIndexOf(''substring''«,''startpos''«, ''charcount''»»)</code> |Cobra |returns −1 |- |<code>''string'' lastIndexOfString:''substring''</code> |Smalltalk |returns 0 |- |<code>string last ''substring string startpos''</code> |Tcl |returns −1 |- |<code>{{codett|2=apl|1=(⌽<\⌽}}''substring''{{codett|2=apl|1=⍷'string')⍳1}}</code> |APL |returns −1 |- | <code>''string''.rfind(''substring'')</code> | Rust<ref>See the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.rfind <code>str::rfind</code>] method.</ref> | returns {{mono|None}} |}
<syntaxhighlight lang="lisp"> ; Examples in Common Lisp (search "e" "Hello mate" :from-end t) ; returns 9 (search "z" "word" :from-end t) ; returns NIL </syntaxhighlight>
<syntaxhighlight lang="csharp"> // Examples in C# "Hello mate".LastIndexOf("e"); // returns 9 "Hello mate".LastIndexOf("e", 4); // returns 1 "word".LastIndexOf("z"); // returns -1 </syntaxhighlight>
<syntaxhighlight lang="perl"> # Examples in Perl 5 rindex("Hello mate", "e"); # returns 9 rindex("Hello mate", "e", 4); # returns 1 rindex("word", "z"); # returns -1 </syntaxhighlight>
<syntaxhighlight lang="raku"> # Examples in Raku "Hello mate".rindex("e"); # returns 9 "Hello mate".rindex("e", 4); # returns 1 "word".rindex('z'); # returns Nil </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Examples in Visual Basic InStrRev("Hello mate", "e") ' returns 10 InStrRev(5, "Hello mate", "e") ' returns 2 InStrRev("word", "z") ' returns 0 </syntaxhighlight>
<!-- endsection -->
===right=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>right(''string'',''n'')</code> returns string |- ! Description | Returns the right ''n'' part of a string. If ''n'' is greater than the length of the string then most implementations return the whole string (exceptions exist – see code examples). |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- |<code>{{codett|2=ada|1=string (string'Last -}} ''n'' {{codett|2=ada|1=+ 1 .. string'Last)}}</code> |Ada |- | <code>Right(''string'',''n'')</code> |VB |- | <code>RIGHT$(''string'',''n'')</code> |BASIC |- | <code>right(''string'',''n'')</code> |FreeBASIC, Ingres, Pick Basic |- | <code>strcpy(''string2'', ''string''+''n'')</code> ({{mono|''n''}} must not be greater than the length of {{mono|''string''}}) |C |- | <code>''string''.Substring(''string''.Length()-''n'')</code> |C# |- | <code>''string''[len(''string'')-''n'':]</code> |Go |- | <code>''string''.substring(''string''.length()-''n'')</code> |Java |- | <code>''string''.slice(-''n'')</code> |JavaScript<ref>{{cite web |url=https://es5.github.com/#x15.5.4.13 |title=Annotated ES5 |publisher=Es5.github.com |access-date=2013-08-18 |archive-date=2013-01-28 |archive-url=https://web.archive.org/web/20130128185825/https://es5.github.com/#x15.5.4.13 |url-status=dead }}</ref> |- | <code>right(''string'',''n'' «,''padchar''»)</code> |Rexx, Erlang |- | <code>substr(''string'',-''n'')</code> |Perl 5, PHP |- | <code>substr(''string'',*-''n'')</code><br><code>''string''.substr(*-''n'')</code> |Raku |- | <code>''string''[-''n'':]</code> |Cobra, Python |- | <code>${''string_param'': -''n''}</code> (a space occurs after the colon) |Bash |- | <code>''string''[''n'']</code> |Pick Basic |- | <code>(string-take-right ''string'' ''n'')</code> |Scheme (SRFI 13) |- | <code>''string''[-''n''..-1]</code> |Ruby |- | <code>''string''[$-''n'' .. $]</code> |D<ref>if n is larger than length of string, then in Debug mode ArrayRangeException is thrown, and unspecified behaviour in Release mode</ref> |- | <code>String.sub ''string'' (String.length ''string'' - ''n'') ''n''</code> |OCaml<ref name="ReferenceA"/> |- | <code>string.sub(''string'', -''n'')</code><br><code>(''string''):sub(-''n'')</code> |Lua |- | <code>''string'' last: ''n''</code> |Smalltalk (Squeak, Pharo) |- | <code>StringTake[''string'', -''n'']</code> |Mathematica<ref name="ReferenceB"/> |- | <code>''string'' (1:''n'')</code> | COBOL |- |<code>''¯n''↑''string''.</code> |APL |- | <code>''string''[n..]</code><br><code>''string''.get(n..)</code> | Rust<ref name="Rust indexing" /> |}
<syntaxhighlight lang="java"> // Examples in Java; extract rightmost 4 characters String str = "CarDoor"; str.substring(str.length()-4); // returns 'Door' </syntaxhighlight>
<syntaxhighlight lang="raku"> # Examples in Raku "abcde".substr(*-3); # returns "cde" "abcde".substr(*-8); # 'out of range' error </syntaxhighlight>
<syntaxhighlight lang="rexx"> /* Examples in Rexx */ right("abcde", 3) /* returns "cde" */ right("abcde", 8) /* returns " abcde" */ right("abcde", 8, "*") /* returns "***abcde" */ </syntaxhighlight>
<syntaxhighlight lang="scheme"> ; Examples in Scheme (use-modules (srfi srfi-13)) (string-take-right "abcde", 3) ; returns "cde" (string-take-right "abcde", 8) ; error </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Examples in Visual Basic Right("sandroguidi", 3) ' returns "idi" Right("sandroguidi", 100) ' returns "sandroguidi" </syntaxhighlight>
<!-- endsection -->
===rpartition=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <string>.rpartition(''separator'') Searches for the separator from right-to-left within the string then returns the sub-string before the separator; the separator; then the sub-string after the separator. |- ! Description | Splits the given string by the right-most separator and returns the three substrings that together make the original. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>''string''.rpartition(''separator'')</code> |Python, Ruby |}
<syntaxhighlight lang="python"> # 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') </syntaxhighlight> <!-- endsection -->
===slice=== ''see'' #substring
<!-- endsection -->
===split=== {| class="wikitable" |- style="background:#fffeed;" ! Definition | <string>.split(''separator''[, ''limit'']) splits a string on separator, optionally only up to a limited number of substrings |- ! Description | Splits the given string by occurrences of the separator (itself a string) and returns a list (or array) of the substrings. If ''limit'' is given, after ''limit'' – 1 separators have been read, the rest of the string is made into the last substring, regardless of whether it has any separators in it. The Scheme and Erlang implementations are similar but differ in several ways. JavaScript differs also in that it cuts, it does not put the rest of the string into the last element. [https://www.w3schools.com/jsref/jsref_split.asp See the example here]. The Cobra implementation will default to whitespace. Opposite of ''join''. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>split(/''separator''/, ''string''«, ''limit''»)</code> |Perl 5 |- | <code>split(''separator'', ''string''«, ''limit''»)</code><br><code>''string''.split(''separator'', «''limit''»)</code> |Raku |- | <code>explode(''separator'', ''string''«, ''limit''»)</code> |PHP |- | <code>''string''.split(''separator''«, ''limit''-1»)</code> |Python |- | <code>''string''.split(''separator''«, ''limit''»)</code> |JavaScript, Java, Ruby |- | <code>string:tokens(''string'', ''sepchars'')</code> |Erlang |- | <code>strings.Split(''string'', ''separator'')</code><br><code>strings.SplitN(''string'', ''separator'', ''limit'')</code> |Go |- | <code>(string-tokenize ''string''« ''charset''« ''start''« ''end''»»»)</code> |Scheme (SRFI 13) |- | <code>Split(''string'', ''sepchars''«, ''limit''»)</code> |VB |- | <code>''string''.Split(''sepchars''«, ''limit''«, ''options''»»)</code> |VB .NET, C#, F# |- | <code>''string'' -split ''separator''«, ''limit''«, ''options''»»</code> |Windows PowerShell |- | <code>Str.split (Str.regexp_string ''separator'') ''string''</code> |OCaml |- | <code>std.string.split(''string'', ''separator'')</code> |D |- | <code>[''string'' componentsSeparatedByString:''separator'']</code> |Objective-C (<code>NSString *</code> only) |- | <code>''string''.componentsSeparatedByString(''separator'')</code> |Swift (Foundation) |- |<code>TStringList.Delimiter, TStringList.DelimitedText</code> |Object Pascal |- | <code>StringSplit[''string'', ''separator''«, ''limit''»]</code> |Mathematica |- | <code>''string''.split«(''sepchars''«, ''limit''«, ''options''»»)»</code> |Cobra |- |<code>split ''string separator''</code> |Tcl |- | <code>(''separator''≠''string'')⊂''string''</code> in APL2<br><code>''separator''(≠⊆⊢)''string''</code> in Dyalog APL 16.0 |APL |- | <code>''string''.split(''separator'')</code> <code>''string''.split(''limit'', ''separator'')</code> | Rust<ref>See the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.split <code>str::split</code>] and [https://doc.rust-lang.org/stable/std/primitive.str.html#method.rsplit <code>str::rsplit</code>] methods.</ref> |}
<syntaxhighlight lang="csharp"> // Example in C# "abc,defgh,ijk".Split(','); // {"abc", "defgh", "ijk"} "abc,defgh;ijk".Split(',', ';'); // {"abc", "defgh", "ijk"} </syntaxhighlight>
<syntaxhighlight lang="erlang"> % Example in Erlang string:tokens("abc;defgh;ijk", ";"). % ["abc", "defgh", "ijk"] </syntaxhighlight>
<syntaxhighlight lang="java"> // Examples in Java "abc,defgh,ijk".split(","); // {"abc", "defgh", "ijk"} "abc,defgh;ijk".split(",|;"); // {"abc", "defgh", "ijk"} </syntaxhighlight>
<syntaxhighlight lang="pascal"> { Example in Pascal } var 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; </syntaxhighlight>
<syntaxhighlight lang="perl"> # Examples in Perl 5 split(/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') </syntaxhighlight>
<syntaxhighlight lang="raku"> # 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) </syntaxhighlight>
<!-- endsection -->
===sprintf=== ''see'' #Format
===strip=== ''see'' #trim
<!-- endsection -->
===strcmp=== ''see'' #Compare (integer result)
<!-- endsection -->
===substring=== {{hatnote|See CharAt for base of startpos/endpos.}}
{| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>substring(''string'', ''startpos'', ''endpos'')</code> returns string<br><code>substr(''string'', ''startpos'', ''numChars'')</code> returns string |- ! Description | Returns a substring of ''string'' between starting at ''startpos'' and ''endpos'', or starting at ''startpos'' of length ''numChars''. The resulting string is truncated if there are fewer than ''numChars'' characters beyond the starting point. ''endpos'' represents the index after the last character in the substring. For variable-length encodings such as UTF-8, UTF-16 or Shift-JIS, it can be necessary to remove string positions at the end, to avoid invalid strings. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- |<code>string[''startpos'':''endpos'']</code> |ALGOL 68 (changes base index) |- |<code>string (''startpos'' .. ''endpos'')</code> |Ada (changes base index) |- | <code>Mid(''string'', ''startpos'', ''numChars'')</code> |VB |- | <code>mid(''string'', ''startpos'', ''numChars'')</code> |FreeBASIC |- | <code>''string''[''startpos''+(⍳''numChars'')-~⎕IO]</code> |APL |- | <code>MID$(''string'', ''startpos'', ''numChars'')</code> |BASIC |- | <code>substr(''string'', ''startpos'', ''numChars'')</code> |AWK (changes string), Perl 5,<ref name="substr2"/><ref name="substr4"/> PHP<ref name="substr2"/><ref name="substr4"/> |- | <code>substr(''string'', ''startpos'', ''numChars'')</code><br><code>''string''.substr(''startpos'', ''numChars'')</code> |Raku<ref name="substr5"/><ref name="substr6"/> |- | <code>substr(''string'', ''startpos'' «,''numChars'', ''padChar''»)</code> |PL/I |- | <code>substr(''string'', ''startpos'' «,''numChars'', ''padChar''»)</code> |Rexx |- | <code>''string''[''startpos'':''endpos'']</code> |Cobra, Python,<ref name="substr2"/><ref name="substr3"/> Go |- | <code>''string''[''startpos'', ''numChars'']</code> |Pick Basic |- | <code>''string''[''startpos'', ''numChars'']</code><br><code>''string''[''startpos'' .. ''endpos''-1]</code><br><code>''string''[''startpos'' ... ''endpos'']</code> |Ruby<ref name="substr2"/><ref name="substr3"/> |- | <code>''string''[''startpos'' .. ''endpos'']</code><br><code>''string''[''startpos'' len ''numChars'']</code> |Seed7 |- | <code>''string''.slice(''startpos''«, ''endpos''»)</code> |JavaScript<ref name="substr2"/><ref name="substr3"/> |- | <code>''string''.substr(''startpos''«, ''numChars''»)</code> |C++ (STL), JavaScript |- | <code>''string''.Substring(''startpos'', ''numChars'')</code> |VB .NET, C#, Windows PowerShell, F# |- | <code>''string''.substring(''startpos''«, ''endpos''»)</code> |Java, JavaScript |- | <code>copy(''string'', ''startpos'', ''numChars'')</code> |Object Pascal (Delphi) |- | <code>(substring ''string'' ''startpos'' ''endpos'')</code> |Scheme |- | <code>(subseq ''string'' ''startpos'' ''endpos'')</code> |Common Lisp |- | <code>(subseq ''string'' ''startpos'' ''endpos'')</code> |ISLISP |- | <code>String.sub ''string'' ''startpos'' ''numChars''</code> |OCaml |- | <code>substring (''string'', ''startpos'', ''numChars'')</code> |Standard ML |- | <code>string:sub_string(''string'', ''startpos'', ''endpos'')</code><br><code>string:substr(''string'', ''startpos'', ''numChars'')</code> |Erlang |- | <code>strncpy(''result'', ''string'' + ''startpos'', ''numChars'');</code> |C |- | <code>''string''[''startpos'' .. ''endpos''+1]</code> |D |- | <code>take ''numChars'' $ drop ''startpos'' ''string''</code> |Haskell |- | <code>[''string'' substringWithRange:NSMakeRange(''startpos'', ''numChars'')]</code> |Objective-C (<code>NSString *</code> only) |- | <code>''string''.[''startpos''..''endpos'']</code> |F# |- | <code>string.sub(''string'', ''startpos'', ''endpos'')</code><br><code>(''string''):sub(''startpos'', ''endpos'')</code> |Lua<ref name="substr2"/><ref name="substr3"/> |- | <code>''string'' copyFrom: ''startpos'' to: ''endpos''</code> |Smalltalk |- | <code>''string''(''startpos'':''endpos'')</code> |Fortran |- | <code>SUBSTRING(''string'' FROM ''startpos'' «FOR ''numChars''»)</code> |SQL |- | <code>StringTake[''string'', {''startpos'', ''endpos''}]</code> |Mathematica<ref name="substr2"/><ref name="substr3"/> |- | <code>''string'' (''startpos'':''numChars'')</code> | COBOL |- | <code>${''string_param'':''startpos'':''numChars''}</code> | Bash |- | <code>string range ''string startpos endpos''</code> |Tcl |- | <code>''string''[''startpos''..''endpos'']</code><br><code>''string''.get(''startpos''..''endpos'')</code> | Rust<ref name="Rust indexing" /> |}
<syntaxhighlight lang="csharp"> // Examples in C# "abc".Substring(1, 1): // returns "b" "abc".Substring(1, 2); // returns "bc" "abc".Substring(1, 6); // error </syntaxhighlight>
<syntaxhighlight lang="lisp"> ;; Examples in Common Lisp (subseq "abc" 1 2) ; returns "b" (subseq "abc" 2) ; returns "c" </syntaxhighlight>
<syntaxhighlight lang="erlang"> % Examples in Erlang string:substr("abc", 2, 1). % returns "b" string:substr("abc", 2). % returns "bc" </syntaxhighlight>
<syntaxhighlight lang="perl"> # Examples in Perl 5 substr("abc", 1, 1); # returns "b" substr("abc", 1); # returns "bc" </syntaxhighlight>
<syntaxhighlight lang="raku"> # Examples in Raku "abc".substr(1, 1); # returns "b" "abc".substr(1); # returns "bc" </syntaxhighlight>
<syntaxhighlight lang="python"> # Examples in Python "abc"[1:2] # returns "b" "abc"[1:3] # returns "bc" </syntaxhighlight>
<syntaxhighlight lang="rexx"> /* 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****" */ </syntaxhighlight>
<!-- endsection -->
===Uppercase=== <!-- startsection --> {| class="wikitable" |- style="background:#fffeed;" ! Definition | <code>uppercase(''string'')</code> returns string |- ! Description | Returns the string in upper case. |} {| class="wikitable sortable" |- style="text-align:left;" ! Format !! Languages |- | <code>UCase(''string'')</code> |VB |- | <code>ucase(''string'')</code> |FreeBASIC |- | <code>toupper(''string'')</code> |AWK (changes string) |- | <code>uc(''string'')</code> |Perl, Raku |- | <code>''string''.uc</code> |Raku |- |<code>toupper(''char'')</code> |C (operates on one character) |- |<code>{{codett|2=c|1=for (size_t i = 0, len = strlen(}}''string''); i< len; i++) ''string''[i] = toupper(''string''[i]);</code><br><code>{{codett|2=c|1=for (char* c =}} ''string''{{codett|2=c|1=; *c != '\0'; c++) *c = toupper(*c);}}</code> |C (string / char array) |- | <code>std.string.toUpper(''string'')</code> |D |- | <code>transform(''string''.begin(), ''string''.end(), ''result''.begin(), toupper)<ref name="cpptransform" /></code> | C++<ref><code>std::string</code> only, result is stored in string ''result'' which is at least as long as ''string'', and may or may not be ''string'' itself</ref> |- | <code>uppercase(''string'')</code> |Object Pascal (Delphi) |- |<code>upcase(''char'')</code> |Object Pascal (Delphi) (operates on one character) |- | <code>strtoupper(''string'')</code> |PHP |- | <code>upper(''string'')</code> |Seed7 |- |<code>${''string_param''^^}</code> (mnemonic: ^ is pointing up) |Bash |- |<code>echo "string" <nowiki>|</nowiki> tr 'a-z' 'A-Z'</code> |Unix |- | <code>translate(''string'')</code><br><code>UPPER variables</code><br>{{code|PARSE UPPER VAR SrcVar DstVar|rexx}} |Rexx |- | <code>''string''.upper()</code> |Python |- | <code>upcase(''string'')</code> |Pick Basic |- | <code>''string''.upcase</code> |Ruby<ref name="ReferenceC"/> |- | <code>strings.ToUpper(''string'')</code> |Go |- | <code>(string-upcase ''string'')</code> |Scheme, Common Lisp |- | <code>String.uppercase ''string''</code> |OCaml |- | <code>String.map Char.toUpper ''string''</code> |Standard ML |- | <code>map Char.toUpper ''string''</code> |Haskell |- | <code>''string''.toUpperCase()</code> |Java, JavaScript |- | <code>''string''.uppercase()</code> |Kotlin<ref>{{cite web |title=uppercase - Kotlin Programming Language |url=https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/uppercase.html |website=Kotlin |access-date=9 November 2024 |language=en}}</ref> |- | <code>to_upper(''string'')</code> |Erlang |- | <code>''string''.ToUpper()</code> |VB .NET, C#, Windows PowerShell, F# |- | <code>''string''.uppercaseString</code> |Objective-C (<code>NSString *</code> only), Swift (Foundation) |- | <code>string.upper(''string'')</code><br><code>(''string''):upper()</code> |Lua |- | <code>''string'' asUppercase</code> |Smalltalk |- | <code>UPPER(''string'')</code> |SQL |- | <code>ToUpperCase[''string'']</code> |Mathematica |- | <code>{{codett|«FUNCTION» UPPER-CASE(|cobolfree}}''string'')</code> |COBOL |- | <code>''string''.toUpper</code> |Cobra |- | <code>string toupper ''string''</code> | Tcl |- | <code>''string''.to_uppercase()</code> | Rust<ref>In Rust, the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.to_uppercase <code>str::to_uppercase</code>] method returns a newly allocated [https://doc.rust-lang.org/stable/std/string/struct.String.html <code>String</code>] with any lowercase characters changed to uppercase ones following the Unicode rules.</ref> |}
<syntaxhighlight lang="csharp"> // Example in C# "Wiki means fast?".ToUpper(); // "WIKI MEANS FAST?" </syntaxhighlight>
<syntaxhighlight lang="perl"> # Example in Perl 5 uc("Wiki means fast?"); # "WIKI MEANS FAST?" </syntaxhighlight>
<syntaxhighlight lang="raku"> # Example in Raku uc("Wiki means fast?"); # "WIKI MEANS FAST?" "Wiki means fast?".uc; # "WIKI MEANS FAST?" </syntaxhighlight>
<syntaxhighlight lang="rexx"> /* 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." */ </syntaxhighlight>
<syntaxhighlight lang="scheme"> ; Example in Scheme (use-modules (srfi srfi-13)) (string-upcase "Wiki means fast?") ; "WIKI MEANS FAST?" </syntaxhighlight>
<syntaxhighlight lang="vbnet"> ' Example in Visual Basic UCase("Wiki means fast?") ' "WIKI MEANS FAST?" </syntaxhighlight> <!-- endsection -->
===trim=== {{main|Trim (programming)}} '''<code>trim</code>''' or '''<code>strip</code>''' is used to remove whitespace from the beginning, end, or both beginning and end, of a string.
{| class="wikitable" |- style="text-align:left;" ! Example usage !! Languages |- | <code>''String''.Trim([''chars''])</code> |C#, VB.NET, Windows PowerShell |- | <code>''string''.strip();</code> |D |- | <code>(.trim ''string'')</code> |Clojure |- |<code>''sequence'' [ predicate? ] trim</code> |Factor |- | <code>{{codett|(string-trim '(#\Space #\Tab #\Newline)|lisp}} ''string'')</code> |Common Lisp |- | <code>(string-trim ''string'')</code> |Scheme |- | <code>''string''.trim()</code> |Java, JavaScript (1.8.1+, Firefox 3.5+), Rust<ref>In Rust, the [https://doc.rust-lang.org/stable/std/primitive.str.html#method.trim <code>str::trim</code>] method returns a reference to the original <code>&str</code>.</ref> |- | <code>Trim(''String'')</code> |Pascal,<ref>{{cite web|url=http://gnu-pascal.de/gpc-hr/Trim.html |title=Trim – GNU Pascal priručnik |publisher=Gnu-pascal.de |access-date=2013-08-24}}</ref> QBasic, Visual Basic, Delphi |- | <code>''string''.strip()</code> |Python |- | <code>strings.Trim(''string'', ''chars'')</code> |Go |- | <code>LTRIM(RTRIM(''String''))</code> |Oracle SQL, T-SQL |- | <code>strip(''string'' [,''option'', ''char''])</code> |REXX |- | <code>string:strip(''string'' [,''option'', ''char''])</code> |Erlang |- | <code>''string''.strip</code><br><code>''string''.lstrip</code><br><code>''string''.rstrip</code> |Ruby |- | <code>''string''.trim</code> |Raku |- | <code>trim(''string'')</code> |PHP, Raku |- | <code>[''string'' {{codett|stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]|objc}}</code> |Objective-C using Cocoa |- | <code>''string'' withBlanksTrimmed</code><br><code>''string'' withoutSpaces</code><br><code>''string'' withoutSeparators</code> |Smalltalk (Squeak, Pharo)<br>Smalltalk |- |<code>strip(string)</code> |SAS |- |<code>string trim ''$string''</code> |Tcl |- | <code>TRIM(''string'')</code><br><code>TRIM(ADJUSTL(''string''))</code> |Fortran |- | <code>TRIM(''string'')</code> |SQL |- | <code>TRIM(''string'')</code><br><code>LTrim(''string'')</code><br><code>RTrim(''String'')</code> |ColdFusion |- | <code>String.trim ''string''</code> |OCaml 4+ |}
'''Other languages'''
In languages without a built-in trim function, it is usually simple to create a custom function which accomplishes the same task.
====APL==== APL can use regular expressions directly: <syntaxhighlight lang="apl"> Trim←'^ +| +$'⎕R'' </syntaxhighlight> Alternatively, a functional approach combining Boolean masks that filter away leading and trailing spaces: <syntaxhighlight lang="apl"> Trim←{⍵/⍨(∨\∧∘⌽∨\∘⌽)' '≠⍵} </syntaxhighlight> Or reverse and remove leading spaces, twice: <syntaxhighlight lang="apl"> Trim←{(∨\' '≠⍵)/⍵}∘⌽⍣2 </syntaxhighlight>
====AWK==== In AWK, one can use regular expressions to trim:
<syntaxhighlight lang="awk"> ltrim(v) = gsub(/^[ \t]+/, "", v) rtrim(v) = gsub(/[ \t]+$/, "", v) trim(v) = ltrim(v); rtrim(v) </syntaxhighlight>
or:
<syntaxhighlight lang="awk"> function ltrim(s) { sub(/^[ \t]+/, "", s); return s } function rtrim(s) { sub(/[ \t]+$/, "", s); return s } function trim(s) { return rtrim(ltrim(s)); } </syntaxhighlight>
====C/C++==== There is no standard trim function in C or C++. Most of the available string libraries<ref>{{cite web|url=http://www.and.org/vstr/comparison |title=String library comparison |publisher=And.org |access-date=2013-08-24}}</ref> for C contain code which implements trimming, or functions that significantly ease an efficient implementation. The function has also often been called '''EatWhitespace''' in some non-standard C libraries.
In C, programmers often combine a ltrim and rtrim to implement trim:
<syntaxhighlight lang="c"> #include <ctype.h> #include <string.h>
void rtrim(char* str) { char* s; s = str + strlen(str); while (--s >= str) { if (!isspace(*s)) { break; } *s = 0; } }
void ltrim(char* str) { size_t n; n = 0; while (str[n] && isspace((unsigned char) str[n])) { n++; } memmove(str, str + n, strlen(str) - n + 1); }
void trim(char* str) { rtrim(str); ltrim(str); } </syntaxhighlight>
The open source C++ library Boost has several trim variants, including a standard one:<ref>{{cite web|url=http://www.boost.org/doc/html/string_algo/usage.html#id2742817 |title=Usage – 1.54.0 |publisher=Boost.org |date=2013-05-22 |access-date=2013-08-24}}</ref>
<syntaxhighlight lang="cpp"> #include <boost/algorithm/string/trim.hpp>
trimmed = boost::algorithm::trim_copy("string"); </syntaxhighlight>
With boost's function named simply <code>trim</code> the input sequence is modified in-place, and returns no result.
Another open source C++ library Qt, has several trim variants, including a standard one:<ref>[http://doc.trolltech.com/4.5/qstring.html#trimmed] {{webarchive |url=https://web.archive.org/web/20090802041055/http://doc.trolltech.com/4.5/qstring.html#trimmed |date=August 2, 2009 }}</ref>
<syntaxhighlight lang="cpp"> #include <QString>
trimmed = s.trimmed(); </syntaxhighlight>
The Linux kernel also includes a strip function, <code>strstrip()</code>, since 2.6.18-rc1, which trims the string "in place". Since 2.6.33-rc1, the kernel uses <code>strim()</code> instead of <code>strstrip()</code> to avoid false warnings.<ref>{{cite web|author=dankamongmen |url=https://github.com/dankamongmen/sprezzos-kernel-packaging/blob/master/changelog |title=sprezzos-kernel-packaging/changelog at master · dankamongmen/sprezzos-kernel-packaging · GitHub |publisher=Github.com |access-date=2016-05-29}}</ref>
====Haskell==== A trim algorithm in Haskell:
<syntaxhighlight lang="haskell"> import Data.Char (isSpace) trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace </syntaxhighlight>
may be interpreted as follows: ''f'' drops the preceding whitespace, and reverses the string. ''f'' is then again applied to its own output. The type signature (the second line) is optional.
====J====
The trim algorithm in J is a functional description:
<syntaxhighlight lang="j"> trim =. #~ [: (+./\ *. +./\.) ' '&~: </syntaxhighlight>
That is: filter (<code>#~</code>) for non-space characters (<code>' '&~:</code>) between leading (<code>+./\</code>) and (<code>*.</code>) trailing (<code>+./\.</code>) spaces.
====JavaScript==== There is a built-in trim function in JavaScript 1.8.1 (Firefox 3.5 and later), and the ECMAScript 5 standard. In earlier versions it can be added to the String object's prototype as follows:
<syntaxhighlight lang="javascript"> String.prototype.trim = function() { return this.replace(/^\s+/g, "").replace(/\s+$/g, ""); }; </syntaxhighlight>
====Perl==== Perl 5 has no built-in trim function. However, the functionality is commonly achieved using regular expressions.
Example: <syntaxhighlight lang="perl"> $string =~ s/^\s+//; # remove leading whitespace $string =~ s/\s+$//; # remove trailing whitespace </syntaxhighlight> or: <syntaxhighlight lang="perl"> $string =~ s/^\s+|\s+$//g ; # remove both leading and trailing whitespace </syntaxhighlight> These examples modify the value of the original variable <code>$string</code>.
Also available for Perl is '''StripLTSpace''' in <code>String::Strip</code> from CPAN.
There are, however, two functions that are commonly used to strip whitespace from the end of strings, <code>chomp</code> and <code>chop</code>: * <code>[http://perldoc.perl.org/functions/chop.html chop]</code> removes the last character from a string and returns it. * <code>[http://perldoc.perl.org/functions/chomp.html chomp]</code> removes the trailing newline character(s) from a string if present. (What constitutes a newline is [http://perldoc.perl.org/perlvar.html $INPUT_RECORD_SEPARATOR] dependent).
In Raku, the upcoming sister language of Perl, strings have a <code>trim</code> method.
Example: <syntaxhighlight lang="raku"> $string = $string.trim; # remove leading and trailing whitespace $string .= trim; # same thing </syntaxhighlight>
====Tcl==== The Tcl <code>string</code> command has three relevant subcommands: <code>trim</code>, <code>trimright</code> and <code>trimleft</code>. 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:
<syntaxhighlight lang="tcl"> set string onomatopoeia set trimmed [string trim $string aeiou] ;# result is nomatop set r_trimmed [string trimright $string aeiou] ;# result is onomatop set l_trimmed [string trimleft $string aeiou] ;# result is nomatopoeia </syntaxhighlight>
====XSLT==== XSLT includes the function <code>normalize-space(''string'')</code> which strips leading and trailing whitespace, in addition to replacing any whitespace sequence (including line breaks) with one space.
Example: <syntaxhighlight lang="xml"> <xsl:variable name='trimmed'> <xsl:value-of select='normalize-space(string)'/> </xsl:variable> </syntaxhighlight> XSLT 2.0 includes regular expressions, providing another mechanism to perform string trimming.
Another XSLT technique for trimming is to utilize the XPath 2.0 <code>substring()</code> function.
==References== {{Reflist|refs= <ref name="at1">the index can be negative, which then indicates the number of places before the end of the string.</ref> <ref name="at2">the index can '''not''' be negative, use '''*-N''' where N indicate the number of places before the end of the string.</ref>
<ref name="substr2">''<code>startpos</code>'' can be negative, which indicates to start that number of places before the end of the string.</ref> <ref name="substr3">''<code>endpos</code>'' can be negative, which indicates to end that number of places before the end of the string.</ref> <ref name="substr4">''<code>numChars</code>'' can be negative, which indicates to end that number of places before the end of the string.</ref> <ref name="substr5">''<code>startpos</code>'' can '''not''' be negative, use ''* - startpos'' to indicate to start that number of places before the end of the string.</ref> <ref name="substr6">''<code>numChars</code>'' can '''not''' be negative, use ''* - numChars'' to indicate to end that number of places before the end of the string.</ref> }}
Programming language comparison *String functions <!-- Hidden categories below --> Category:Articles with example Ada code Category:Articles with example ALGOL 68 code Category:Articles with example BASIC code Category:Articles with example C code Category:Articles with example C++ code Category:Articles with example C Sharp code Category:Articles with example Fortran code Category:Articles with example Haskell code Category:Articles with example Java code Category:Articles with example JavaScript code Category:Articles with example Julia code Category:Articles with example Lisp (programming language) code Category:Articles with example OCaml code Category:Articles with example Pascal code Category:Articles with example Perl code Category:Articles with example PHP code Category:Articles with example Python (programming language) code Category:Articles with example Rust code Category:Articles with example Smalltalk code Category:Articles with example Swift code