Articulo de referencia

Comparación de lenguajes de programación (funciones de cadena)

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

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 nil

Concatenació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 0

Encontrar

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 0

localizar

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 0

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

ver #Comparar (resultado entero)

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"
 # Ejemplos en Raku "abc" .substr ( 1 , 1 ); # devuelve "b" " abc " .substr ( 1 ); # devuelve "bc"
# Ejemplos en Python "abc" [ 1 : 2 ] # devuelve "b" "abc" [ 1 : 3 ] # devuelve "bc"
/* Ejemplos en Rexx */ substr ( "abc" , 2 , 1 ) /* devuelve "b" */ substr ( "abc" , 2 ) /* devuelve "bc" */ substr ( "abc" , 2 , 6 ) /* devuelve "bc " */ substr ( "abc" , 2 , 6 , "*" ) /* devuelve "bc****" */

Mayúsculas

// Ejemplo en C# "¿Wiki significa rápido?" . ToUpper (); // "¿WIKI SIGNIFICA RÁPIDO?"
# Ejemplo en Perl 5 uc ( "Wiki significa rápido?" ); # "WIKI SIGNIFICA RÁPIDO?"
# Ejemplo en Raku uc ( "Wiki significa rápido?" ); # "WIKI SIGNIFICA RÁPIDO?" "Wiki significa rápido?" . uc ; # "WIKI SIGNIFICA RÁPIDO?"
/* Ejemplo en Rexx */ translate ( "Wiki significa rápido?" ) /* "WIKI SIGNIFICA RÁPIDO?" *//* Ejemplo n.º 2 */ A = 'Este es un ejemplo.' MAYÚSCULA A /* "ESTE ES UN EJEMPLO." *//* Ejemplo #3 */ A = 'mayúsculas usando la función Translate.' Translate UPPER VAR A Z /* Z="MAYÚSCULAS USANDO LA FUNCIÓN TRANSLATE." */
; Ejemplo en Scheme ( use-modules ( srfi srfi-13 )) ( string-upcase "Wiki significa rápido?" ) ; "WIKI SIGNIFICA RÁPIDO?"
' Ejemplo en Visual Basic UCase ( "Wiki significa rápido?" ) ' "WIKI SIGNIFICA RÁPIDO?"

recortar

trimo stripse utiliza para eliminar espacios en blanco del principio, del final o de ambos, de una cadena.

Otros idiomas

En los lenguajes que no tienen una función de recorte integrada, suele ser sencillo crear una función personalizada que realice la misma tarea.

APL

APL puede utilizar expresiones regulares directamente:

Recortar '^ +| +$' ⎕R ''

Como alternativa, se puede adoptar un enfoque funcional que combine máscaras booleanas que filtren los espacios iniciales y finales:

Recortar { /⍨ ( \ ⌽∨ \∘ ) ' ' }

O bien, invierta el proceso y elimine los espacios iniciales, dos veces:

Recortar { ( \ ' ' ) / } 2

AWK

En AWK , se pueden usar expresiones regulares para recortar:

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

o:

function ltrim ( s ) { sub ( /^[ \t]+/ , "" , s ); return s } function rtrim ( s ) { sub ( /[ \t]+$/ , "" , s ); return s } function trim ( s ) { return rtrim ( ltrim ( s )); }

C/C++

No existe una función de recorte estándar en C ni en C++. La mayoría de las bibliotecas de cadenas disponibles [ 58 ] para C contienen código que implementa el recorte o funciones que facilitan considerablemente una implementación eficiente. En algunas bibliotecas no estándar de C, esta función también se conoce como EatWhitespace .

En C, los programadores suelen combinar ltrim y rtrim para implementar trim:

#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 ); }

La biblioteca de código abierto C++ Boost tiene varias variantes de recorte, incluida una estándar: [ 59 ]

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

Con la función de Boost, cuyo nombre es simplemente [nombre de trimla función], la secuencia de entrada se modifica directamente y no devuelve ningún resultado.

Otra biblioteca C++ de código abierto , Qt , tiene varias variantes de recorte, incluida una estándar: [ 60 ]

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

El kernel de Linux también incluye una función strip, strstrip(), desde la versión 2.6.18-rc1, que recorta la cadena "in situ". Desde la versión 2.6.33-rc1, el kernel utiliza strim()en lugar de strstrip()para evitar falsas advertencias. [ 61 ]

Haskell

Un algoritmo de recorte en Haskell :

import Data.Char ( isSpace ) trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace

Puede interpretarse de la siguiente manera: f elimina el espacio en blanco precedente e invierte la cadena. Luego, f se aplica nuevamente a su propia salida. La firma de tipo (la segunda línea) es opcional.

J

El algoritmo de recorte en J es una descripción funcional :

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

Es decir: filtrar ( #~) para caracteres que no sean espacios ( ' '&~:) entre espacios iniciales ( +./\) y espacios *.finales ( ).+./\.

JavaScript

Existe una función de recorte integrada en JavaScript 1.8.1 (Firefox 3.5 y versiones posteriores), y en el estándar ECMAScript 5. En versiones anteriores, se puede agregar al prototipo del objeto String de la siguiente manera:

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

Perl

Perl 5 no tiene una función de recorte integrada. Sin embargo, esta funcionalidad se suele lograr mediante expresiones regulares .

Ejemplo:

$string =~ s/^\s+// ; # elimina el espacio en blanco inicial $string =~ s/\s+$// ; # elimina el espacio en blanco final

o:

$string =~ s/^\s+|\s+$//g ; # elimina los espacios en blanco iniciales y finales

Estos ejemplos modifican el valor de la variable original $string.

También está disponible para Perl StripLTSpace en String::StripCPAN .

Sin embargo, existen dos funciones que se utilizan comúnmente para eliminar los espacios en blanco del final de las cadenas, chompy chop:

  • chopElimina el último carácter de una cadena y lo devuelve.
  • chompElimina el/los carácter/es de salto de línea final/es de una cadena si están presentes. (Lo que constituye un salto de línea depende de $INPUT_RECORD_SEPARATOR ).

En Raku , el próximo lenguaje hermano de Perl, las cadenas tienen un trimmétodo.

Ejemplo:

$string = $string . trim ; # elimina los espacios en blanco iniciales y finales $string .= trim ; # lo mismo

Tcl

El comando Tclstring tiene tres subcomandos relevantes: trim, trimrighty trimleft. Para cada uno de esos comandos, se puede especificar un argumento adicional: una cadena que representa un conjunto de caracteres a eliminar; el valor predeterminado es el espacio en blanco (espacio, tabulación, salto de línea, retorno de carro).

Ejemplo de cómo recortar vocales:

establecer cadena onomatopoeia establecer recortado [ cadena recortar $cadena aeiou ] ; # el resultado es nomatop establecer r_recortado [ cadena recortar derecha $cadena aeiou ] ; # el resultado es onomatop establecer l_recortado [ cadena recortar izquierda $cadena aeiou ] ; # el resultado es nomatopoeia

XSLT

XSLT incluye una función que elimina los espacios en blanco iniciales y finales, además de reemplazar cualquier secuencia de espacios en blanco (incluidos los saltos de línea) por un solo espacio.normalize-space(string)

Ejemplo:

<xsl:variable name= 'trimmed' > <xsl:value-of select= 'normalize-space(string)' /> </xsl:variable>

XSLT 2.0 incluye expresiones regulares, lo que proporciona otro mecanismo para realizar el recorte de cadenas.

Otra técnica XSLT para recortar consiste en utilizar la substring()función XPath 2.0.

Referencias

  1. "Tutoriales web en línea de W3Schools" . www.w3schools.com . Consultado el 14 de abril de 2026 .
  2. 1 2 3 4 5 El índice puede ser negativo, lo que indica el número de lugares antes del final de la cadena.
  3. En Rust, elstr::charsmétodo itera sobre puntos de código y elstd::iter::Iterator::nthmétodo en iteradores devuelve el enésimo valor indexado desde cero del iterador, oNone.
  4. El índice no puede ser negativo; utilice *-N, donde N indica el número de lugares antes del final de la cadena.
  5. En C++, eloperator<=>método sobrecargado en una cadena devuelve unstd::strong_orderingobjeto (de lo contrariostd::weak_ordering):less,equal(igual queequivalent), ogreater.
  6. devuelve MENOR, IGUAL o MAYOR
  7. devuelve LT, EQ o GT
  8. devuelve.TRUE.o.FALSE.. Estas funciones se basan en la secuencia de intercalación ASCII.
  9. 1 2 Extensión de IBM.
  10. En Rust, elOrd::cmpmétodo en una cadena devuelve unOrdering:Less,Equal, oGreater.
  11. El REXX original usaba ¬ para la negación lógica, el REXX ANSI usa \, algunas implementaciones aceptan ~ o ^, y las implementaciones que no son EBCDIC varían en cuanto a si ¬ está en el punto de código AA o AC.
  12. El PL/I original usaba ¬ para la negación lógica, algunas implementaciones esperan ^, y las implementaciones que no son EBCDIC varían en cuanto a si ¬ está en el punto de código AA o AC.
  13. 123456In Rust, the operators == and != and the methods eq, ne are implemented by the PartialEq trait, and the operators <, >, <=, >= and the methods lt, gt, le, ge are implemented by the PartialOrd trait.
  14. The operators use the compiler's default collating sequence.
  15. modifies string1, which must have enough space to store the result
  16. In Rust, the + operator is implemented by the Add trait.
  17. See the str::contains method.
  18. See the std::basic_string::contains method.
  19. 12startpos is IBM extension.
  20. 12See the str::find method.
  21. startpos is IBM extension.
  22. "scan in Fortran Wiki". Fortranwiki.org. 2009-04-30. Retrieved 2013-08-18.
  23. "verify in Fortran Wiki". Fortranwiki.org. 2012-05-03. Retrieved 2013-08-18.
  24. formatstring must be a fixed literal at compile time for it to have the correct type.
  25. See std::format, which is imported by the Rust prelude so that it can be used under the name format.
  26. See the slice::join method.
  27. if n is larger than the length of the string, then in Debug mode ArrayRangeException is thrown, in Release mode, the behaviour is unspecified.
  28. if n is larger than the length of the string, Java will throw an IndexOutOfBoundsException
  29. 12if n is larger than length of string, raises Invalid_argument
  30. 12if n is larger than length of string, throw the message "StringTake::take:"
  31. 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, including Range (0..n), RangeFrom (n..), and RangeTo (..n) because they all implement the SliceIndex trait with str being the type being indexed. The str::get method is the non-panicking way to index. It returns None in the cases in which indexing would panic.
  32. Ruby lacks Unicode support
  33. See the str::len method.
  34. In Rust, the str::chars method iterates over code points and the std::iter::Iterator::count method on iterators consumes the iterator and returns the total number of elements in the iterator.
  35. operates on one character
  36. 12The transform function exists in the std:: namespace. You must include the <algorithm> header file to use it. The tolower and toupper functions are in the global namespace, obtained by the <ctype.h> header file. The std::tolower and std::toupper names are overloaded and cannot be passed to std::transform without a cast to resolve a function overloading ambiguity, e.g. std::transform(string.begin(), string.end(), result.begin(), (int (*)(int))std::tolower);
  37. std::string only, result is stored in string result which is at least as long as string, and may or may not be string itself
  38. 12only ASCII characters as Ruby lacks Unicode support
  39. See the str::to_lowercase method.
  40. See the str::replace method.
  41. 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.
  42. third parameter is non-standard
  43. In Rust, the str::chars method iterates over code points, the std::iter::Iterator::rev method on reversible iterators (std::iter::DoubleEndedIterator) creates a reversed iterator, and the std::iter::Iterator::collect method consumes the iterator and creates a collection (which here is specified as a String with the turbofish syntax) from the iterator's elements.
  44. See the str::rfind method.
  45. "Annotated ES5". Es5.github.com. Archived from the original on 2013-01-28. Retrieved 2013-08-18.
  46. if n is larger than length of string, then in Debug mode ArrayRangeException is thrown, and unspecified behaviour in Release mode
  47. See the str::split and str::rsplit methods.
  48. 1234567startpos can be negative, which indicates to start that number of places before the end of the string.
  49. 12numChars can be negative, which indicates to end that number of places before the end of the string.
  50. startpos can not be negative, use * - startpos to indicate to start that number of places before the end of the string.
  51. numChars can not be negative, use * - numChars to indicate to end that number of places before the end of the string.
  52. 12345endpos can be negative, which indicates to end that number of places before the end of the string.
  53. std::string only, result is stored in string result which is at least as long as string, and may or may not be string itself
  54. "mayúsculas - Lenguaje de programación Kotlin" . Kotlin . Consultado el 9 de noviembre de 2024 .
  55. En Rust, elstr::to_uppercasemétodo devuelve una nueva instancia asignadaStringcon todos los caracteres en minúscula cambiados a mayúsculas siguiendo las reglas de Unicode.
  56. En Rust, elstr::trimmétodo devuelve una referencia al original&str.
  57. «Recortar – GNU Pascal priručnik» . Gnu-pascal.de . Consultado el 24 de agosto de 2013 .
  58. "Comparación de bibliotecas de cadenas" . And.org . Consultado el 24 de agosto de 2013 .
  59. "Uso – 1.54.0" . Boost.org. 22 de mayo de 2013. Consultado el 24 de agosto de 2013 .
  60. Archivado el 2 de agosto de 2009 en Wayback Machine .
  61. dankamongmen. "sprezzos-kernel-packaging/changelog en master · dankamongmen/sprezzos-kernel-packaging · GitHub" . Github.com . Consultado el 29 de mayo de 2016 .