Las funciones de cadena se utilizan en los lenguajes de programación informática para manipular una cadena o consultar información sobre una cadena (algunas hacen ambas cosas).
La mayoría de los lenguajes de programación que admiten el tipo de dato cadena incluyen funciones específicas para cadenas, aunque dentro de cada lenguaje pueden existir otras formas de manejarlas directamente a nivel de bajo nivel. En los lenguajes orientados a objetos, las funciones de cadena suelen implementarse como propiedades y métodos de objetos de cadena. En los lenguajes funcionales y basados en listas, una cadena se representa como una lista (de códigos de caracteres); por lo tanto, todos los procedimientos de manipulación de listas pueden considerarse funciones de cadena. Sin embargo, estos lenguajes también pueden implementar un subconjunto de funciones específicas para cadenas.
Para las funciones que manipulan cadenas, los lenguajes modernos orientados a objetos, como C# y Java , utilizan cadenas inmutables y devuelven una copia (en memoria dinámica recién asignada), mientras que otros, como C, manipulan la cadena original a menos que el programador copie los datos a una nueva cadena. Véase, por ejemplo, la concatenación más abajo.
El ejemplo más básico de una función de cadena es la length(string)función. Esta función devuelve la longitud de una cadena literal .
- Por ejemplo,
length("hello world")devolvería 11.
Otros lenguajes pueden tener funciones de cadena con sintaxis, parámetros o resultados similares o idénticos. Por ejemplo, en muchos lenguajes, la función de longitud se suele representar como len(cadena) . La siguiente lista de funciones comunes pretende ayudar a evitar esta confusión.
Funciones comunes de cadenas de caracteres (referencia multilingüe)
A continuación se enumeran las funciones de cadena comunes a muchos lenguajes, incluyendo los diferentes nombres que se utilizan. La siguiente lista de funciones comunes tiene como objetivo ayudar a los programadores a encontrar la función equivalente en un lenguaje. La concatenación de cadenas y las expresiones regulares se tratan en páginas separadas. Las instrucciones entre comillas simples (« … ») son opcionales. [ 1 ]
CharAt
{ Ejemplo en Pascal } var MyStr : string = 'Hola, Mundo' ; MyChar : Char ; begin MyChar := MyStr [ 2 ] ; // 'e'# Ejemplo en ALGOL 68 # "Hola, mundo"[2]; // 'e'
// Ejemplo en C #include <stdio.h>char myStr1 [] = "Hola, Mundo" ; printf ( "%c" , * ( myStr1 + 1 )); // 'e' printf ( "%c" , * ( myStr1 + 7 )); // 'W' printf ( "%c" , myStr1 [ 11 ]); // 'd' printf ( "%s" , myStr1 ); // 'Hola, Mundo' printf ( "%s" , "Hola(2), Mundo(2)" ); // 'Hola(2), Mundo(2)'importar std ;usando std :: string ;char myStr1 [] = "Hola(1), Mundo(1)" ; string myStr2 = "Hola(2), Mundo(2)" ; std :: println ( "Hola(3), Mundo(3)" ); // 'Hola(3 ) , Mundo(3)' std :: println ( " {}" , myStr2 [ 6 ]); // '2' std :: println ( "{}" , myStr1.substr ( 5 , 3 )); // '(1)'// Ejemplo en C# "Hola, Mundo" [ 2 ]; // 'l'# Ejemplo en Perl 5 substr ( "Hola, Mundo" , 1 , 1 ); # 'e'# Ejemplos en Python "Hola, mundo" [ 2 ] # 'l' "Hola, mundo" [ - 3 ] # 'r'# Ejemplo en Raku "Hola, Mundo" . substr ( 1 , 1 ); # 'e'' Ejemplo en Visual Basic Mid ( "Hola, mundo" , 2 , 1 )' Ejemplo en Visual Basic .NET "Hola, mundo" . Caracteres ( 2 ) ' "l"c" Ejemplo en Smalltalk " 'Hola, mundo' en: 2 . "$e"//Ejemplo en Rust "Hola, mundo" . chars (). nth ( 2 ); // Some('l')Comparar (resultado entero)
# Ejemplo en Perl 5 "hello" cmp "world" ; # devuelve -1# Ejemplo en Python cmp ( "hello" , "world" ) # devuelve -1# Ejemplos en Raku "hello" cmp "world" ; # devuelve Less "world" cmp "hello" ; # devuelve More "hello" cmp "hello" ; # devuelve Same/** Ejemplo en Rexx */ compare ( "hello" , "world" ) /* devuelve el índice de discrepancia: 1 */; Ejemplo en Scheme ( use-modules ( srfi srfi-13 )) ; devuelve el índice de discrepancia: 0 ( string-compare "hello" "world" values values values )Comparar (basado en operadores relacionales, resultado booleano)
% Ejemplo en Erlang "hello" > "world" . % devuelve falso# Ejemplo en Raku "arte" > "pintura" ; # devuelve Falso "arte" < "pintura" ; # devuelve Verdadero# Ejemplo en Windows PowerShell "hello" -gt "world" # devuelve falso;; Ejemplo en Common Lisp ( string> "arte" "pintura" ) ; devuelve nil ( string< "arte" "pintura" ) ; devuelve un valor distinto de nilConcatenación
{ Ejemplo en Pascal } 'abc' + 'def' ; // devuelve "abcdef"// Ejemplo en C# "abc" + "def" ; // devuelve "abcdef"' Ejemplo en Visual Basic "abc" & "def" ' devuelve "abcdef" "abc" + "def" ' devuelve "abcdef" "abc" & Null ' devuelve "abc" "abc" + Null ' devuelve Null// Ejemplo en D "abc" ~ "def" ; // devuelve "abcdef";; Ejemplo en common lisp ( concatenar 'cadena "abc " "def " "ghi" ) ; devuelve "abc def ghi"# Ejemplo en Perl 5 "abc" . "def" ; # devuelve "abcdef" "Perl " . 5 ; # devuelve "Perl 5"/* Ejemplo en PL/I */ "abc" || "def" /* devuelve "abcdef" */# Ejemplo en Raku "abc" ~ "def" ; # devuelve "abcdef" "Perl " ~ 6 ; # devuelve "Perl 6"/* Ejemplo en Rexx */ "Strike" 2 /* devuelve "Strike2" */ "Strike" 2 /* devuelve "Strike 2" */Contiene
¢ Ejemplo en ALGOL 68 ¢ cadena en cadena("e", loc int , "Hola amigo"); ¢ devuelve verdadero ¢ cadena en cadena("z", loc int , "palabra"); ¢ devuelve falso ¢
// Ejemplo en C# "Hola amigo" .Contains ( "e" ); // devuelve verdadero " palabra" .Contains ( " z" ); // devuelve falso# Ejemplo en Python "e" en "Hola amigo" # devuelve verdadero "z" en "palabra" # devuelve falso # Ejemplo en Raku " ¡ Buenos días!" . contains ( ' z ' ) # devuelve False" Ejemplo en Smalltalk " 'Hola amigo' includesSubstring: 'e' " devuelve verdadero " ' palabra ' includesSubstring: 'z' " devuelve falso "Igualdad
Comprueba si dos cadenas son iguales. Véase también #Compare y #Compare . Realizar comprobaciones de igualdad mediante una comparación genérica con un resultado entero no solo resulta confuso para el programador, sino que a menudo es una operación mucho más costosa; esto es especialmente cierto cuando se utilizan " cadenas C ".
// Ejemplo en C# "hello" == "world" // devuelve false' Ejemplo en Visual Basic "hello" = "world" ' devuelve falso# Ejemplos en Perl 5 'hello' eq 'world' # devuelve 0 'hello' eq 'hello' # devuelve 1# Ejemplos en Raku 'hello' eq 'world' # devuelve False 'hello' eq 'hello' # devuelve True# Ejemplo en Windows PowerShell "hello" -eq "world" # devuelve falso⍝ Ejemplo en APL 'hello' ≡ 'world' ⍝ devuelve 0Encontrar
Ejemplos
- Lisp común
( búsqueda "e" "Hola amigo" ) ; devuelve 1 ( búsqueda "z" "palabra" ) ; devuelve NIL
- DO#
"Hola amigo" . IndexOf ( "e" ); // devuelve 1 "Hola amigo" . IndexOf ( "e" , 4 ); // devuelve 9 "palabra" . IndexOf ( "z" ); // devuelve -1
- Raku
"¡Hola!" . index ( 'e' ) # devuelve 1 "¡Hola!" . index ( 'z' ) # devuelve Nil
- Esquema
( use-modules ( srfi srfi-13 )) ( string-contains "Hello mate" "e" ) ; devuelve 1 ( string-contains "word" "z" ) ; devuelve #f
- Visual Basic
' Ejemplos en InStr ( "Hola amigo" , "e" ) ' devuelve 2 InStr ( 5 , "Hola amigo" , "e" ) ' devuelve 10 InStr ( "palabra" , "z" ) ' devuelve 0
- Charla informal
'Hola amigo' indexOfSubCollection: 'ate' "devuelve 8"
'Hola amigo' indexOfSubCollection: 'tarde' "devuelve 0"
Yo ' Hola amigo ' indexOfSubCollection: 'tarde' ifAbsent: [ 99 ] "devuelve 99"
'Hola amigo' indexOfSubCollection: 'tarde' ifAbsent: [ error propio ] "genera una excepción"
Encuentra el personaje
// Ejemplos en C# "Hola amigo" . IndexOf ( 'e' ); // devuelve 1 "palabra" . IndexOf ( 'z' ) // devuelve -1; Ejemplos en Common Lisp ( posición #\e "Hola compañero" ) ; devuelve 1 ( posición #\z "palabra" ) ; devuelve NIL^a Dado un conjunto de caracteres, SCAN devuelve la posición del primer carácter encontrado, [ 22 ] mientras que VERIFY devuelve la posición del primer carácter que no pertenece al conjunto. [ 23 ]
Formato
// Ejemplo en C# String . Format ( "Mi {0} cuesta {1:C2}" , "pen" , 19.99 ); // devuelve "Mi bolígrafo cuesta $19.99"// Ejemplo en formato Object Pascal (Delphi) ( 'Mi %s cuesta $%2f' , [ 'bolígrafo' , 1 9.99 ]) ; // devuelve "Mi bolígrafo cuesta $19.99"// Ejemplo en Java String.format ( "Mi %s cuesta $%2f" , "pen" , 19.99 ); // devuelve "Mi bolígrafo cuesta $19.99"# Ejemplos en Raku sprintf "Mi %s cuesta $%.2f" , "pen" , 19.99 ; # devuelve "Mi bolígrafo cuesta $19.99" 1 . fmt ( "%04d" ); # devuelve "0001"# Ejemplo en Python "Mi %s cuesta $ %.2f " % ( "pen" , 19.99 ); # devuelve "Mi bolígrafo cuesta $19.99" "Mi {0} cuesta $ {1:.2f} " . format ( "pen" , 19.99 ); # devuelve "Mi bolígrafo cuesta $19.99"#Ejemplo en Python 3.6+ pen = "pen" f "Mi { pen } cuesta { 19.99 } " #devuelve "Mi bolígrafo cuesta 19.99"; Ejemplo en Scheme ( formato "Mi ~a cuesta $~1,2F" "bolígrafo" 19.99 ) ; devuelve "Mi bolígrafo cuesta $19.99"/* ejemplo en PL/I */ put string ( some_string ) edit ( 'Mi ' , 'bolígrafo' , ' cuesta' , 19.99 )( a , a , a , p '$$$V.99' ) /* devuelve "Mi bolígrafo cuesta $19.99" */Desigualdad
Comprueba si dos cadenas no son iguales. Ver también #Igualdad .
// Ejemplo en C# "hello" != "world" // devuelve true' Ejemplo en Visual Basic "hola" <> "mundo" ' devuelve verdadero;; Ejemplo en Clojure ( not= "hello" "world" ) ; ⇒ true# Ejemplo en Perl 5 'hello' ne 'world' # devuelve 1# Ejemplo en Raku 'hello' ne 'world' # devuelve True# Ejemplo en Windows PowerShell "hello" -ne "world" # devuelve verdaderoíndice
ver #Encontrar
índice de
ver #Encontrar
instr
ver #Encontrar
instrucciones
ver #rfind
unirse
// Ejemplo en C# String . Join ( "-" , { "a" , "b" , "c" }) // "abc"" Ejemplo en Smalltalk " #( 'a' 'b' 'c' ) joinUsing: '-' " 'abc' "# Ejemplo en Perl 5 join ( '-' , ( 'a' , 'b' , 'c' )); # 'abc'# Ejemplo en Raku <ab c> . join ( '-' ); # 'abc'# Ejemplo en Python "-" . join ([ "a" , "b" , "c" ]) # 'abc'# Ejemplo en Ruby [ "a" , "b" , "c" ]. join ( "-" ) # 'abc'; Ejemplo en Scheme ( use-modules ( srfi srfi-13 )) ( string-join ' ( "a" "b" "c" ) "-" ) ; "abc"últimoíndicede
ver #rfind
izquierda
# Ejemplo en Raku "Hello, there!" . substr ( 0 , 6 ); # devuelve "Hello,"/* Ejemplos en Rexx */ left ( "abcde" , 3 ) /* devuelve "abc" */ left ( "abcde" , 8 ) /* devuelve "abcde " */ left ( "abcde" , 8 , "*" ) /* devuelve "abcde***" */; Ejemplos en Scheme ( use-modules ( srfi srfi-13 )) ( string-take "abcde" , 3 ) ; devuelve "abc" ( string-take "abcde" , 8 ) ; error' Ejemplos en Visual Basic Left ( "sandroguidi" , 3 ) ' devuelve "san" Left ( "sandroguidi" , 100 ) ' devuelve "sandroguidi"Len
ver #longitud
longitud
// Ejemplos en C# "hello" . Length ; // devuelve 5 "" . Length ; // devuelve 0# Ejemplos en Erlang string : len ( "hello" ). % devuelve 5 string : len ( "" ). % devuelve 0# Ejemplos en Perl 5 length ( "hello" ); # devuelve 5 length ( "" ); # devuelve 0# Ejemplos en Raku "" . caracteres ; caracteres "" ; # ambos devuelven 0 "" . códigos ; códigos "" ; # ambos devuelven 0' Ejemplos en Visual Basic Len ( "hola" ) ' devuelve 5 Len ( "" ) ' devuelve 0//Ejemplos en Objective-C [ @"hello" Longitud ] //devuelve 5 [ @"" Longitud ] //devuelve 0-- Ejemplos en Lua ( "hello" ): len () -- devuelve 5 # "" -- devuelve 0localizar
ver #Encontrar
minúsculas
// Ejemplo en C# "¿Wiki significa rápido?" . ToLower (); // "¿wiki significa rápido?"; Ejemplo en Scheme ( use-modules ( srfi srfi-13 )) ( string-downcase "Wiki significa rápido?" ) ; "wiki significa rápido?"/* Ejemplo en C */ #include <ctype.h> #include <stdio.h>int main ( void ) { char s [] = "Wiki significa rápido?" ; for ( int i = 0 ; i < sizeof ( s ) - 1 ; ++ i ) { // transforma los caracteres en su lugar, uno por uno s [ i ] = tolower ( s [ i ]); } printf ( string ); // "wiki significa rápido?" return 0 ; }# Ejemplo en Raku "¿Wiki significa rápido?" . lc ; # "¿wiki significa rápido?"medio
ver #subcadena
dividir
# Ejemplos en 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', "", "")# Ejemplos en 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');reemplazar
// Ejemplos en C# " effffff " .Reemplazar ( "f" , "jump" ); // devuelve "ejumpjumpjumpjumpjumpjump" "blah" .Reemplazar ( "z" , " y" ); // devuelve "blah"// Ejemplos en Java "effffff" .replace ( " f" , "jump" ); // devuelve "ejumpjumpjumpjumpjumpjump" "effffff" .replaceAll ( " f*" , "jump" ); // devuelve "ejump"// Ejemplos en Raku "effffff" . subst ( "f" , "jump" , : g ); # devuelve "ejumpjumpjumpjumpjumpjump" "blah" . subst ( "z" , "y" , : g ); # devuelve "blah"' Ejemplos en Visual Basic Reemplazar ( "effffff" , "f" , "jump" ) ' devuelve "ejumpjumpjumpjumpjumpjump" Reemplazar ( "blah" , "z" , "y" ) ' devuelve "blah"# Ejemplos en Windows PowerShell "effffff" -replace "f" , "jump" # devuelve "ejumpjumpjumpjumpjumpjump" "effffff" -replace "f*" , "jump" # devuelve "ejump"contrarrestar
" Ejemplo en Smalltalk " 'hello' al revés " devuelve 'olleh' "# Ejemplo en Perl 5: "hola" inverso # devuelve "olleh"# Ejemplo en Raku "hello" .flip # devuelve " olleh"# Ejemplo en Python "hello" [:: - 1 ] # devuelve "olleh"; Ejemplo en Scheme ( use-modules ( srfi srfi-13 )) ( string-reverse "hello" ) ; devuelve "olleh"rfind
; Ejemplos en Common Lisp ( búsqueda "e" "Hola amigo" :desde-el-fin t ) ; devuelve 9 ( búsqueda "z" "palabra" :desde-el-fin t ) ; devuelve NIL// Ejemplos en C# " Hola amigo" .LastIndexOf ( "e" ); // devuelve 9 "Hola amigo" .LastIndexOf ( "e" , 4 ); // devuelve 1 "palabra" .LastIndexOf ( " z" ); // devuelve -1# Ejemplos en Perl 5 rindex ( "Hola amigo" , "e" ); # devuelve 9 rindex ( "Hola amigo" , "e" , 4 ); # devuelve 1 rindex ( "palabra" , "z" ); # devuelve -1# Ejemplos en Raku "Hola amigo" . rindex ( "e" ); # devuelve 9 "Hola amigo" . rindex ( "e" , 4 ); # devuelve 1 "palabra" . rindex ( 'z' ); # devuelve Nil' Ejemplos en Visual Basic InStrRev ( "Hola amigo" , "e" ) ' devuelve 10 InStrRev ( 5 , "Hola amigo" , "e" ) ' devuelve 2 InStrRev ( "palabra" , "z" ) ' devuelve 0bien
// Ejemplos en Java; extrae los 4 caracteres más a la derecha String str = "CarDoor" ; str . substring ( str . length () - 4 ); // devuelve 'Door'# Ejemplos en Raku "abcde" .substr (*- 3 ); # devuelve "cde" "abcde" .substr (*- 8 ); # error 'fuera de rango '/* Ejemplos en Rexx */ right ( "abcde" , 3 ) /* devuelve "cde" */ right ( "abcde" , 8 ) /* devuelve " abcde" */ right ( "abcde" , 8 , "*" ) /* devuelve "***abcde" */; Ejemplos en Scheme ( use-modules ( srfi srfi-13 )) ( string-take-right "abcde" , 3 ) ; devuelve "cde" ( string-take-right "abcde" , 8 ) ; error' Ejemplos en Visual Basic Right ( "sandroguidi" , 3 ) ' devuelve "idi" Right ( "sandroguidi" , 100 ) ' devuelve "sandroguidi"rpartición
# Ejemplos en 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')rebanada
ver #subcadena
dividir
// Ejemplo en C# "abc,defgh,ijk" . Split ( ',' ); // {"abc", "defgh", "ijk"} "abc,defgh;ijk" . Split ( ',' , ';' ); // {"abc", "defgh", "ijk"}% Ejemplo en Erlang string : tokens ( "abc;defgh;ijk" , ";" ). % ["abc", "defgh", "ijk"]// Ejemplos en Java "abc,defgh,ijk" . split ( "," ); // {"abc", "defgh", "ijk"} "abc,defgh;ijk" . split ( ",|;" ); // {"abc", "defgh", "ijk"}{ Ejemplo en 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 ;# Ejemplos en Perl 5 split ( /spam/ , 'Huevos de spam spam spam y jamón' ); # ('Huevos de spam ', ' ', ' y jamón') split ( /X/ , 'Huevos de spam spam spam y jamón' ); # ('Huevos de spam spam spam y jamón')# Ejemplos en Raku 'Spam eggs spam spam and ham' . split ( /spam/ ); # (Spam eggs and ham) split ( /X/ , 'Spam eggs spam spam and ham' ); # (Spam eggs spam spam and ham)sprintf
ver #Formato
banda
ver #recorte
strcmp
subcadena
// Ejemplos en C# "abc" .Substring ( 1 , 1 ): // devuelve "b" " abc" .Substring ( 1 , 2 ); // devuelve "bc" "abc" .Substring ( 1 , 6 ) ; // error;; Ejemplos en Common Lisp ( subseq "abc" 1 2 ) ; devuelve "b" ( subseq "abc" 2 ) ; devuelve "c"% Ejemplos en Erlang string : substr ( "abc" , 2 , 1 ). % devuelve "b" string : substr ( "abc" , 2 ). % devuelve "bc"# Ejemplos en Perl 5 substr ( "abc" , 1 , 1 ); # devuelve "b" substr ( "abc" , 1 ); # devuelve "bc"# Examples in Raku"abc".substr(1, 1); # returns "b""abc".substr(1); # returns "bc"# Examples in Python"abc"[1:2]# returns "b""abc"[1:3]# returns "bc"/* Examples in Rexx */substr("abc",2,1)/* returns "b" */substr("abc",2)/* returns "bc" */substr("abc",2,6)/* returns "bc " */substr("abc",2,6,"*")/* returns "bc****" */Uppercase
// Example in C#"Wiki means fast?".ToUpper();// "WIKI MEANS FAST?"# Example in Perl 5uc("Wiki means fast?");# "WIKI MEANS FAST?"# Example in Rakuuc("Wiki means fast?"); # "WIKI MEANS FAST?""Wiki means fast?".uc; # "WIKI MEANS FAST?"/* Example in Rexx */translate("Wiki means fast?")/* "WIKI MEANS FAST?" *//* Example #2 */ A='This is an example.' UPPERA/* "THIS IS AN EXAMPLE." *//* Example #3 */ A='upper using Translate Function.' TranslateUPPERVARAZ/* Z="UPPER USING TRANSLATE FUNCTION." */; Example in Scheme(use-modules(srfisrfi-13))(string-upcase"Wiki means fast?"); "WIKI MEANS FAST?"' Example in Visual BasicUCase("Wiki means fast?")' "WIKI MEANS FAST?"trim
trim or strip is used to remove whitespace from the beginning, end, or both beginning and end, of a string.
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:
Trim←'^ +| +$'⎕R''Alternatively, a functional approach combining Boolean masks that filter away leading and trailing spaces:
Trim←{⍵/⍨(∨\∧∘⌽∨\∘⌽)' '≠⍵}Or reverse and remove leading spaces, twice:
Trim←{(∨\' '≠⍵)/⍵}∘⌽⍣2AWK
In AWK, one can use regular expressions to trim:
ltrim(v)=gsub(/^[ \t]+/,"",v)rtrim(v)=gsub(/[ \t]+$/,"",v)trim(v)=ltrim(v);rtrim(v)or:
functionltrim(s){sub(/^[ \t]+/,"",s);returns}functionrtrim(s){sub(/[ \t]+$/,"",s);returns}functiontrim(s){returnrtrim(ltrim(s));}C/C++
There is no standard trim function in C or C++. Most of the available string libraries[58] 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:
#include<ctype.h>#include<string.h>voidrtrim(char*str){char*s;s=str+strlen(str);while(--s>=str){if(!isspace(*s)){break;}*s=0;}}voidltrim(char*str){size_tn;n=0;while(str[n]&&isspace((unsignedchar)str[n])){n++;}memmove(str,str+n,strlen(str)-n+1);}voidtrim(char*str){rtrim(str);ltrim(str);}The open source C++ library Boost has several trim variants, including a standard one:[59]
#include<boost/algorithm/string/trim.hpp>trimmed=boost::algorithm::trim_copy("string");With boost's function named simply trim 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:[60]
#include<QString>trimmed=s.trimmed();The Linux kernel also includes a strip function, strstrip(), since 2.6.18-rc1, which trims the string "in place". Since 2.6.33-rc1, the kernel uses strim() instead of strstrip() to avoid false warnings.[61]
Haskell
A trim algorithm in Haskell:
importData.Char(isSpace)trim::String->Stringtrim=f.fwheref=reverse.dropWhileisSpacemay 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:
trim=.#~[:(+./\*.+./\.)' '&~:That is: filter (#~) for non-space characters (' '&~:) between leading (+./\) and (*.) trailing (+./\.) spaces.
JavaScript
There is a built-in trim function in JavaScript 1.8.1 (Firefox 3.5 and later), and the ECMAScript 5 standard. In earlier versions it can be added to the String object's prototype as follows:
String.prototype.trim=function(){returnthis.replace(/^\s+/g,"").replace(/\s+$/g,"");};Perl
Perl 5 has no built-in trim function. However, the functionality is commonly achieved using regular expressions.
Example:
$string=~s/^\s+//;# remove leading whitespace$string=~s/\s+$//;# remove trailing whitespaceor:
$string=~s/^\s+|\s+$//g;# remove both leading and trailing whitespaceThese examples modify the value of the original variable $string.
Also available for Perl is StripLTSpace in String::Strip from CPAN.
There are, however, two functions that are commonly used to strip whitespace from the end of strings, chomp and chop:
chopremoves the last character from a string and returns it.chompremoves the trailing newline character(s) from a string if present. (What constitutes a newline is $INPUT_RECORD_SEPARATOR dependent).
In Raku, the upcoming sister language of Perl, strings have a trim method.
Example:
$string = $string.trim; # remove leading and trailing whitespace$string .= trim; # same thingTcl
The Tclstring command has three relevant subcommands: trim, trimright and trimleft. For each of those commands, an additional argument may be specified: a string that represents a set of characters to remove—the default is whitespace (space, tab, newline, carriage return).
Example of trimming vowels:
setstringonomatopoeia settrimmed[stringtrim$stringaeiou];# result is nomatopsetr_trimmed[stringtrimright$stringaeiou];# result is onomatopsetl_trimmed[stringtrimleft$stringaeiou];# result is nomatopoeiaXSLT
XSLT includes the function normalize-space(string) which strips leading and trailing whitespace, in addition to replacing any whitespace sequence (including line breaks) with one space.
Example:
<xsl:variablename='trimmed'><xsl:value-ofselect='normalize-space(string)'/></xsl:variable>XSLT 2.0 includes regular expressions, providing another mechanism to perform string trimming.
Another XSLT technique for trimming is to utilize the XPath 2.0 substring() function.
References
- ↑"W3Schools Online Web Tutorials". www.w3schools.com. Retrieved 2026-04-14.
- 12345the index can be negative, which then indicates the number of places before the end of the string.
- ↑In Rust, the
str::charsmethod iterates over code points and thestd::iter::Iterator::nthmethod on iterators returns the zero-indexed nth value from the iterator, orNone. - ↑the index can not be negative, use *-N where N indicate the number of places before the end of the string.
- ↑In C++, the overloaded
operator<=>method on a string returns astd::strong_orderingobject (otherwisestd::weak_ordering):less,equal(same asequivalent), orgreater. - ↑returns LESS, EQUAL, or GREATER
- ↑returns LT, EQ, or GT
- ↑returns
.TRUE.or.FALSE.. These functions are based on the ASCII collating sequence. - 12IBM extension.
- ↑In Rust, the
Ord::cmpmethod on a string returns anOrdering:Less,Equal, orGreater. - ↑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.
- ↑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.
- 123456In Rust, the operators == and != and the methods
eq,neare implemented by thePartialEqtrait, and the operators <, >, <=, >= and the methodslt,gt,le,geare implemented by thePartialOrdtrait. - ↑The operators use the compiler's default collating sequence.
- ↑modifies
string1, which must have enough space to store the result - ↑In Rust, the
+operator is implemented by theAddtrait. - ↑See the
str::containsmethod. - ↑See the
std::basic_string::containsmethod. - 12startpos is IBM extension.
- 12See the
str::findmethod. - ↑
startposis IBM extension. - ↑"scan in Fortran Wiki". Fortranwiki.org. 2009-04-30. Retrieved 2013-08-18.
- ↑"verify in Fortran Wiki". Fortranwiki.org. 2012-05-03. Retrieved 2013-08-18.
- ↑
formatstringmust be a fixed literal at compile time for it to have the correct type. - ↑See
std::format, which is imported by the Rust prelude so that it can be used under the nameformat. - ↑See the
slice::joinmethod. - ↑if n is larger than the length of the string, then in Debug mode ArrayRangeException is thrown, in Release mode, the behaviour is unspecified.
- ↑if n is larger than the length of the string, Java will throw an IndexOutOfBoundsException
- 12if n is larger than length of string, raises Invalid_argument
- 12if n is larger than length of string, throw the message "StringTake::take:"
- 123In 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
&str(string reference) can be indexed by various types of ranges, includingRange(0..n),RangeFrom(n..), andRangeTo(..n) because they all implement theSliceIndextrait withstrbeing the type being indexed. Thestr::getmethod is the non-panicking way to index. It returnsNonein the cases in which indexing would panic. - ↑Ruby lacks Unicode support
- ↑See the
str::lenmethod. - ↑In Rust, the
str::charsmethod iterates over code points and thestd::iter::Iterator::countmethod on iterators consumes the iterator and returns the total number of elements in the iterator. - ↑operates on one character
- 12The
transformfunction exists in thestd::namespace. You must include the<algorithm>header file to use it. Thetolowerandtoupperfunctions are in the global namespace, obtained by the<ctype.h>header file. Thestd::tolowerandstd::touppernames are overloaded and cannot be passed tostd::transformwithout a cast to resolve a function overloading ambiguity, e.g.std::transform(string.begin(), string.end(), result.begin(), (int (*)(int))std::tolower); - ↑
std::stringonly, result is stored in stringresultwhich is at least as long asstring, and may or may not bestringitself - 12only ASCII characters as Ruby lacks Unicode support
- ↑See the
str::to_lowercasemethod. - ↑See the
str::replacemethod. - 12345The "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.
- ↑third parameter is non-standard
- ↑In Rust, the
str::charsmethod iterates over code points, thestd::iter::Iterator::revmethod on reversible iterators (std::iter::DoubleEndedIterator) creates a reversed iterator, and thestd::iter::Iterator::collectmethod consumes the iterator and creates a collection (which here is specified as aStringwith the turbofish syntax) from the iterator's elements. - ↑See the
str::rfindmethod. - ↑"Annotated ES5". Es5.github.com. Archived from the original on 2013-01-28. Retrieved 2013-08-18.
- ↑if n is larger than length of string, then in Debug mode ArrayRangeException is thrown, and unspecified behaviour in Release mode
- ↑See the
str::splitandstr::rsplitmethods. - 1234567
startposcan be negative, which indicates to start that number of places before the end of the string. - 12
numCharscan be negative, which indicates to end that number of places before the end of the string. - ↑
startposcan not be negative, use * - startpos to indicate to start that number of places before the end of the string. - ↑
numCharscan not be negative, use * - numChars to indicate to end that number of places before the end of the string. - 12345
endposcan be negative, which indicates to end that number of places before the end of the string. - ↑
std::stringonly, result is stored in string result which is at least as long as string, and may or may not be string itself - ↑ "mayúsculas - Lenguaje de programación Kotlin" . Kotlin . Consultado el 9 de noviembre de 2024 .
- ↑ En Rust, el
str::to_uppercasemétodo devuelve una nueva instancia asignadaStringcon todos los caracteres en minúscula cambiados a mayúsculas siguiendo las reglas de Unicode. - ↑ En Rust, el
str::trimmétodo devuelve una referencia al original&str. - ↑ «Recortar – GNU Pascal priručnik» . Gnu-pascal.de . Consultado el 24 de agosto de 2013 .
- ↑ "Comparación de bibliotecas de cadenas" . And.org . Consultado el 24 de agosto de 2013 .
- ↑ "Uso – 1.54.0" . Boost.org. 22 de mayo de 2013. Consultado el 24 de agosto de 2013 .
- ↑Archivado el 2 de agosto de 2009 en Wayback Machine .
- ↑ dankamongmen. "sprezzos-kernel-packaging/changelog en master · dankamongmen/sprezzos-kernel-packaging · GitHub" . Github.com . Consultado el 29 de mayo de 2016 .
- Cadenas de caracteres (informática)
- Comparación de lenguajes de programación