Article de reference

Comparaison des langages de programmation (fonctions de chaînes de caractères)

Les fonctions de chaînes de caractères sont utilisées dans les langages de programmation informatique pour manipuler une chaîne de caractères ou interroger des informations sur ...

Les fonctions de chaînes de caractères sont utilisées dans les langages de programmation informatique pour manipuler une chaîne de caractères ou interroger des informations sur une chaîne de caractères (certaines font les deux).

La plupart des langages de programmation disposant d'un type de données chaîne de caractères possèdent des fonctions de manipulation de chaînes, bien qu'il existe d'autres méthodes de bas niveau, propres à chaque langage, pour manipuler directement les chaînes. Dans les langages orientés objet, ces fonctions sont souvent implémentées comme des propriétés et des méthodes d'objets chaînes. Dans les langages fonctionnels et les langages basés sur les listes, une chaîne est représentée par une liste (de codes de caractères) ; par conséquent, toutes les procédures de manipulation de listes peuvent être considérées comme des fonctions de chaînes. Cependant, ces langages peuvent également implémenter un sous-ensemble de fonctions spécifiques aux chaînes.

Pour les fonctions manipulant des chaînes de caractères, les langages orientés objet modernes, comme C# et Java, utilisent des chaînes immuables et renvoient une copie (dans une nouvelle zone mémoire dynamique allouée), tandis que d'autres, comme C, modifient la chaîne originale à moins que le programmeur ne copie les données dans une nouvelle chaîne. Voir par exemple la concaténation ci-dessous.

L'exemple le plus simple de fonction de chaîne de caractères est la length(string)fonction `length`. Cette fonction renvoie la longueur d'une chaîne littérale .

par exemple, length("hello world")renverrait 11.

D'autres langages peuvent posséder des fonctions de manipulation de chaînes de caractères présentant une syntaxe, des paramètres ou des résultats similaires, voire identiques. Par exemple, dans de nombreux langages, la fonction longueur est généralement représentée par `len(chaîne)` . La liste ci-dessous des fonctions courantes vise à limiter cette confusion.

La concaténation de chaînes et les expressions régulières sont traitées sur des pages séparées. Les guillemets (« … ») sont facultatifs.

CharAt

DéfinitioncharAt(string,integer)renvoie un caractère.
DescriptionRenvoie le caractère à l'index spécifié dans la chaîne.
ÉquivalentVoir la sous-chaîne de longueur 1 caractère.
FormatLanguesIndice de basestring[i]ALGOL 68 , APL , Julia , Pascal , Object Pascal ( Delphi ), Seed71string[i]C , ++ , C , Cobra , D , FreeBASIC , Go , Python , PHP , Ruby Windows JavaScript , ​​0string{i}PHP (obsolète dans la version 5.3)0string(i)Ada≥1Mid(string,i,1)VB1MID$(string,i,1)BASIQUE1string.Chars(i)VB.NET0string(i:i)Fortran1string.charAt(i)Java , JavaScript0string.[i]OCaml , F#0string.chars().nth(i)Rouille 0string[i,1]Choisissez Basique1String.sub (string, i)ML standard0string!! iHaskell0(string-ref stringi)Schème0(char stringi)Common Lisp0(elt stringi)ISLISP0(get stringi)Clojure0substr(string, i, 1)Perl 5 0substr(string, i, 1)string.substr(i, 1)Raku 0substr(string, i, 1)PL/I1substr(string, i, 1)REXX1string.at(i)C++ (STL) (avec vérification des limites)0lists:nth(i, string)Erlang1[string characterAtIndex:i]Objectif-C ( NSString *uniquement)0string.sub(string, i, i)(string):sub(i, i)Lua 1string at: iSmalltalk (avec vérification des limites)1string index string iTcl0StringTake[string, {i}]Mathematica , langage Wolfram 1string@iEiffel1string (i:1)COBOL1${string_param:i:1}Frapper0istringAPL0 ou 1
; 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)'
; 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)'
[ 2 ]; // 'l'
, 1 , 1 ); # 'e'
[ 2 ] # 'l' "Hello, World" [ - 3 ] # 'r'
.substr ( 1 , 1 ); # 'e '
, 2 , 1 )
. Chars ( 2 ) ' "l"c
'Hello, World' à : 2 . "$e"
.chars ( ). nth ( 2 ); // Some('l')

Comparer (résultat entier)

Définitioncompare(string1,string2)renvoie un entier.DescriptionCompare deux chaînes de caractères. Si elles sont équivalentes, la fonction renvoie zéro. Sinon, la plupart de ces routines renvoient un résultat positif ou négatif selon que la chaîne 1 est respectivement supérieure ou inférieure lexicographiquement à la chaîne 2. Font exception les routines Scheme et Rexx, qui renvoient l'indice de la première différence, et les routines Smalltalk, qui renvoient un code de comparaison indiquant le mode de tri du récepteur par rapport à la chaîne passée en paramètre.
FormatLangues
IF string1<string2 THEN -1 ELSE ABS (string1>string2) FIALGOL 68
cmp(string1, string2)Python 2
(string1 > string2) - (string1 < string2)Python
strcmp(string1, string2)C , PHP
std.string.cmp(string1, string2)D
StrComp(string1, string2)VB , Object Pascal ( Delphi )
string1 cmp string2Perl , Raku
string1 compare: string2Conversation informelle ( Squeak , Pharo )
string1 <=> string2Ruby , C++ (STL, C++20 )
string1.compare(string2)C++ (STL), Swift (Foundation)
compare(string1, string2)Rexx , Seed7
compare(string1, string2, pad)Rexx
CompareStr(string1, string2)Pascal , Objet Pascal ( Delphi )
string1.compareTo(string2)Cobra , Java
string1.CompareTo(string2)VB .NET , C# , F#
(compare string1string2)Clojure
(string= string1string2)Common Lisp
(string-compare string1string2p<p=p>)Schéma (SRFI 13)
(string= string1string2)ISLISP
compare string1string2OCaml
String.compare (string1, string2)ML standard
compare string1string2Haskell
[string]::Compare(string1, string2)Windows PowerShell
[string1 compare:string2]Objectif-C ( NSString *uniquement)
LLT(string1,string2)LLE(string1,string2)LGT(string1,string2)LGE(string1,string2)Fortran
string1.localeCompare(string2)JavaScript
Aller
string compare string1string2Tcl
compare(string1,string2,count)PL/I
string1.cmp(string2)Rouille
cmp "world" ; # renvoie -1
, "world" ) # renvoie -1
cmp "world" ; # renvoie Moins "world" cmp "hello" ; # renvoie Plus "hello" cmp "hello" ; # renvoie Même
, "world" ) /* renvoie l'indice de la différence : 1 */
"world" values ​​values ​​values ​​)

Comparer (opérateur relationnel, résultat booléen)

Définitionstring1 OP string2OU renvoie une valeur booléenne.(compare string1 string2)
DescriptionCompare lexicographiquement deux chaînes de caractères à l'aide d'un opérateur ou d'une fonction relationnelle. Renvoie un résultat booléen.
FormatLangues
string1 OP string2, où OPpeut être n'importe lequel des symboles =, <>, <, >, <= et >=="}},"i":0}}] Pascal , Object Pascal ( Delphi ), OCaml , Seed7 , Standard ML , BASIC , VB , VB.NET , F#
string1 OP string2, où OPpeut prendre n'importe quelle valeur parmi =, /=, ≠, <, >, <=, ≤ et ; également : EQ, NE, LT, LE, GE et GTALGOL 68
(stringOP? string1string2), où OPpeut être n'importe lequel des opérateurs suivants : =, -ci=, <, -ci<, >, -ci>, <=, -ci<=, >= et -ci>= (les opérateurs commençant par ' ' ne sont pas sensibles à la casse)Schème
(stringOP string1string2), où OPpeut être n'importe lequel des opérateurs suivants : =, -ci=, <>, -ci<>, <, -ci<, >, -ci>, <=, -ci<=, >= et -ci>= (les opérateurs commençant par ' -ci ' ne sont pas sensibles à la casse)Schéma (SRFI 13)
(stringOP string1string2), où OPpeut être n'importe lequel des opérateurs suivants : =, -égal, /=, -différent de, <, -inférieur, >, -supérieur, <=, -inférieur, >= et -inférieur (les opérateurs verbaux ne sont pas sensibles à la casse)Common Lisp
(stringOP string1string2), où OPpeut être n'importe lequel des symboles =, /=, <, >, <= et >=ISLISP
string1 OP string2, où OPpeut être n'importe lequel des symboles =, \=, <, >, <= et >= Rexx
string1 OP string2, où OPpeut être n'importe lequel des symboles suivants : =, ¬=, <, >, <=, >=, ¬< et ¬> PL/I
string1 OP string2, où OPpeut être n'importe lequel des symboles =, /=, <, >, <= et >=Ada
string1 OP string2, où OPpeut être n'importe lequel des symboles ==, /=, <, >, =< et >=Erlang
string1 OP string2, où OPpeut être n'importe lequel des symboles ==, /=, <, >, <= et >=Haskell
string1 OP string2, où OPpeut être n'importe lequel des éléments suivants : eq , ne , lt , gt , le et gePerl , Raku
string1 OP string2, où OPpeut être n'importe lequel des symboles ==, !=, <, >, <= et >=C++ (STL), C# , D , Go , JavaScript , Python , PHP , Ruby , Rust , Swift
string1 OP string2, où OPpeut être n'importe lequel des opérateurs suivants : -eq, -ceq, -ne, -cne, -lt, -clt, -gt, -cgt, -le, -cle, -ge et -cge (les opérateurs commençant par ' c ' sont sensibles à la casse)Windows PowerShell
string1 OP string2, où OPpeut être n'importe lequel des symboles ==, ~=, <, >, <= et >=Lua
string1 OP string2, où OPpeut être n'importe lequel des symboles =, ~=, <, >, <= et >=Conversation
string1 OP string2, où OPpeut être n'importe lequel des symboles ==, /=, <, >, <= et >=; De plus : .EQ., .NE., .LT., .LE., .GT. et .GE.Fortran
string1 OP string2OPpeut être n'importe lequel des symboles =, <>, <, >, <=, >= ainsi que leurs équivalents formulésCOBOL
string1 OP string2OPpeut être n'importe lequel des symboles ==, <>, <, >, <= et >=Cobra
string1 OP string2Cette syntaxe est disponible, mais elle compare les pointeurs vers les chaînes, et non leur contenu. Utilisez la fonction Compare(entier).C , Java
string1.METHOD(string2)METHODse trouve l'un des éléments suivants eq: , ne, gt, lt, ge,leRouille
\"world\". % returns false "
% Exemple en Erlang "hello" > "world" . % renvoie faux
-gt "world" # renvoie faux
\"art\" \"painting\") ; returns nil (string< \"art\" \"painting\") ; returns non nil "
Exemple en Common Lisp : `( string< art" "painting" ) ` renvoie `nil` ; `( string< art" "painting" ) ` renvoie une valeur non nulle

Enchaînement

Définitionconcatenate(string1,string2)renvoie une chaîne de caractères.DescriptionConcaténer (joindre) deux chaînes de caractères et renvoyer la chaîne résultante. Dans certains langages, comme le C, les chaînes de caractères sont modifiables ; la seconde chaîne est alors ajoutée à la première et la chaîne ainsi modifiée est renvoyée.
FormatLangues
string1adjacent_tostring2Rexx (culant, équivalent à )string1||string2
string1whitespacestring2Rexx (équivalent à )string1|| ' ' ||string2
string1 & string2Ada , FreeBASIC , Seed7 , BASIC , VB , VB.NET , COBOL (entre littéraux uniquement)
strcat(string1, string2)C , C++ ( uniquement) char*
string1 . string2Perl , PHP
string1 + string2ALGOL 68 , C++ (STL), C# , Cobra , FreeBASIC , Go , Pascal , Object Pascal ( Delphi ), Java , JavaScript , Windows PowerShell , Python , Ruby , Rust , F# , Swift , Turing , VB
string1 ~ string2D , Raku
(string-append string1string2)Schéma , ISLISP
(concatenate 'string string1string2)Common Lisp
(str string1string2)Clojure
string1||string2Rexx , SQL , PL/I
string1 // string2Fortran
string1 ++ string2Erlang , Haskell
string1 ^ string2OCaml , Standard ML , F#
[string1 stringByAppendingString:string2]Objectif-C ( NSString *uniquement)
string1 .. string2Lua
string1 , string2Smalltalk , APL
string1string2SNOBOL
string1string2Frapper
string1 <> string2Mathematica
concaténer la chaîne 1 et la chaîne 2Tcl
+ "def" ; // renvoie "abcdef"
~ "def" ; // renvoie "abcdef"
"def " "ghi" ) ; renvoie "abc def ghi"
. "def" ; # renvoie "abcdef" "Perl " . 5 ; # renvoie "Perl 5"
|| "def" /* renvoie "abcdef" */
~ "def" ; # renvoie "abcdef" "Perl " ~ 6 ; # renvoie "Perl 6"
2 /* renvoie "Strike2" */ "Strike" 2 /* renvoie "Strike 2" */

Contient

Définitioncontains(string,substring)renvoie une valeur booléenne
DescriptionIndique si la chaîne contient la sous- chaîne recherchée. Cela revient à utiliser la fonction Rechercher et à vérifier qu'elle ne génère pas l'erreur mentionnée dans la troisième colonne de la section Rechercher. Cependant, certains langages proposent une méthode plus simple pour exprimer ce test.
En rapportTrouver
FormatLangues
string_in_string(string, loc int, substring)ALGOL 68
ContainsStr(string, substring)Objet Pascal ( Delphi )
strstr(string, substring)!= NULLC , C++ ( char *uniquement)
string.Contains(substring)C# , VB.NET , Windows PowerShell , F#
string.contains(substring)Cobra , Java (1.5+), Raku , Rust , C++ ( C++23 )
string.indexOf(substring) >= 0JavaScript
strpos(string, substring)!== falsePHP
str_contains(string, substring)PHP (8+)
pos(string, substring) <> 0Graine 7
substring in stringCobra , Python (2.3+)
string.find(string, substring) ~= nilLua
string.include?(substring)Rubis
Data.List.isInfixOf substringstringHaskell ( GHC 6.6+)
string includesSubstring: substringSmalltalk ( Squeak , Pharo , Smalltalk/X )
String.isSubstring substringstringML standard
(search substringstring)Common Lisp
ISLISP
(substring? substringstring)Clojure
! StringFreeQ[string, substring]Mathematica
index(string, substring, startpos)>0Choisissez Basique
strings.Contains(string, substring)Aller
string.find(substring)!= string::nposC++
[string containsString:substring]Objective-C ( NSString *uniquement, iOS 8+/OS X 10.10+)
string.rangeOfString(substring)!= nilSwift (Fondation)
∨/substringstringAPL
¢ Exemple en ALGOL 68 ¢ chaîne dans chaîne("e", loc int , "Salut mon pote"); ¢ renvoie vrai ¢ chaîne dans chaîne("z", loc int , "mot"); ¢ renvoie faux ¢
.Contains ( "e" ); // renvoie vrai " word" .Contains ( "z" ); // renvoie faux
. contains ( 'z' ) # renvoie False "¡Buenos días!" . contains ( 'í' ); # renvoie True
'Hello mate' includesSubstring: 'e' " renvoie vrai " ' word ' includesSubstring: 'z' " renvoie faux "

Égalité

Vérifie si deux chaînes de caractères sont égales. Voir aussi `#Compare` et `#Compare` . Effectuer des tests d'égalité via une comparaison générique avec un résultat entier est non seulement source de confusion pour le programmeur, mais s'avère souvent beaucoup plus coûteux ; c'est particulièrement vrai lors de l'utilisation de chaînes de caractères C.

FormatLangues
string1 == string2Python , C++ (STL), C# , Cobra , Go , JavaScript (similitude), PHP (similitude), Ruby , Rust , Erlang , Haskell , Lua , D , Mathematica , Swift
string1 === string2JavaScript , PHP
string1 == string2string1 .EQ. string2Fortran
strcmp(string1, string2) == 0C
(string=? string1string2)Schème
(string= string1string2)Common Lisp , ISLISP
string1 = string2ALGOL 68 , Ada , Object Pascal ( Delphi ), OCaml , Pascal , Rexx , Seed7 , Standard ML , BASIC , VB , VB.NET , F# , Smalltalk , PL/I , COBOL
test string1 = string2[ string1 = string2 ]Bourne Shell
string1 eq string2Perl , Raku , Tcl
string1.equals(string2)Cobra , Java
string1.Equals(string2)C#
string1 -eq string2[string]::Equals(string1, string2)Windows PowerShell
[string1 isEqualToString:string2][string1 isEqual:string2]Objectif-C ( NSString *uniquement)
string1string2APL
string1.eq(string2)Rouille
== "world" // renvoie faux
-eq "world" # renvoie faux
Définitionfind(string,substring)renvoie un entierDescriptionRenvoie la position du début de la première occurrence de la sous-chaîne dans la chaîne . Si la sous-chaîne est introuvable, la plupart de ces routines renvoient une valeur d'index invalide – -1 lorsque les index commencent à 0, 0 lorsqu'ils commencent à 1 – ou une valeur à interpréter comme FAUX (booléen).En rapportinstrrev
FormatLanguesSi introuvable
string in string(substring, pos, string[startpos:])ALGOL 68renvoie BOOL : TRUE ou FALSE, et la position dans REF INT pos.
InStr(«startposstring,substring)VB (les positions commencent à 1)renvoie 0
INSTR$(string,substring)BASIQUE (les positions commencent à 1)renvoie 0
index(string,substring)AWKrenvoie 0
index(string,substring«,startpos»)Perl 5renvoie −1
index(string,substring«,startpos»)string.index(substring,«,startpos»)Rakurenvoie Nul
instr(«startposstring,substring)FreeBASICrenvoie 0
strpos(string,substring«,startpos»)PHPrenvoie FAUX
locate(string, substring)Ingresrenvoie la longueur de la chaîne + 1
strstr(string, substring)C , C++ ( uniquement, renvoie un pointeur vers le premier caractère)char*renvoie NULL
std.string.indexOf(string, substring)Drenvoie −1
pos(string, substring«, startpos»)Graine 7renvoie 0
strings.Index(string, substring)Allerrenvoie −1
pos(substring, string)Pascal , Objet Pascal ( Delphi )renvoie 0
pos(substring, string«,startpos»)Rexxrenvoie 0
string.find(substring«,startpos»)C++ (STL)renvoie std::string::npos
string.find(substring«,startpos«,endpos»»)Pythonrenvoie −1
string.index(substring«,startpos«,endpos»»)génère une erreur de valeur
string.index(substring«,startpos»)Rubisrenvoie nul
string.indexOf(substring«,startpos»)Java , JavaScriptrenvoie −1
string.IndexOf(substring«,startpos«, charcount»»)VB .NET , C# , Windows PowerShell , F#renvoie −1
string:str(string, substring)Erlangrenvoie 0
(string-contains stringsubstring)Schéma (SRFI 13)renvoie #f
(search substringstring)Common Lisprenvoie NIL
(string-index substringstring)ISLISPretoursnil
List.findIndex (List.isPrefixOf substring) (List.tails string)Haskell (renvoie uniquement l'index )ne renvoie rien
Str.search_forward (Str.regexp_string substring) string 0OCamlLève une exception Not_found
Substring.size (#1 (Substring.position substring (Substring.full string)))ML standardrenvoie la longueur de la chaîne
[string rangeOfString:substring].locationObjectif-C ( NSString *uniquement)Renvoie NSNotFound
string.find(string, substring)(string):find(substring)Luarenvoie nul
string indexOfSubCollection: substring startingAt: startpos ifAbsent: aBlockstring findString: substring startingAt: startposConversation informelle ( Squeak , Pharo )L'évaluation de aBlock, qui est une fermeture de bloc (ou tout objet comprenant une valeur), renvoie 0.
startpos = INDEX(string, substring «,back» «, kind»)FortranRenvoie 0 si la sous-chaîne n'est pas présente dans la chaîne ; renvoie LEN(chaîne)+1 si la sous-chaîne est vide.
POSITION(substring IN string)SQLrenvoie 0 (les positions commencent à 1)
index(string, substring, startpos )PL/I renvoie 0 (les positions commencent à 1)
index(string, substring, occurrence )Choisissez BasiqueRenvoie 0 si la sous-chaîne n'est pas présente dans la chaîne ; (les positions commencent à 1)
string.indexOf(substring«,startpos«, charcount»»)Cobrarenvoie −1
string first substring string startposTclrenvoie −1
(substringstring)⍳1APLrenvoie 1 + la dernière position dans la chaîne
string.find(substring)Rouille retoursNone

Exemples

  • Common Lisp
    "Salut mon pote" ) ; renvoie 1 ( recherche "z" "mot" ) ; renvoie NIL
  • C#
    .IndexOf ( "e" ) ; // renvoie 1 "Hello mate" .IndexOf ( " e" , 4 ); // renvoie 9 "word" .IndexOf ( " z" ); // renvoie -1
  • Raku
    . index ( 'e' ) # renvoie 1 "Bonjour !" . index ( 'z' ) # renvoie Nil
  • Schème
    "e" ) ; renvoie 1 ( string-contains "word" "z" ) ; renvoie #f
  • Visual Basic
    , "e" ) ' renvoie 2 InStr ( 5 , "Hello mate" , "e" ) ' renvoie 10 InStr ( "word" , "z" ) ' renvoie 0
  • Conversation

Trouver le personnage

Définitionfind_character(string,char)renvoie un entier
DescriptionRenvoie la position de la première occurrence du caractère `char` dans la chaîne `string` . Si le caractère est introuvable, la plupart de ces fonctions renvoient un index invalide (-1 pour les index commençant à 0, 0 pour les index commençant à 1) ou une valeur booléenne `FALSE`. Ceci peut être réalisé comme un cas particulier de `#Find` , avec une chaîne d'un seul caractère ; cependant, dans de nombreux langages, il peut être plus simple ou plus efficace de localiser directement un seul caractère. De plus, dans de nombreux langages, les caractères et les chaînes de caractères sont considérés comme des types différents, ce qui rend cette fonction utile.
En rapporttrouver
FormatLanguesSi introuvable
char in string(char, pos, string[startpos:])ALGOL 68renvoie BOOL : TRUE ou FALSE , et position dans REF INT pos .FreeBASICrenvoie 0
strchr(string,char)C , C++ ( uniquement, renvoie un pointeur vers un caractère)char*renvoie NULLDrenvoie −1
string.find(char«,startpos»)C++ (STL)renvoie std::string::nposGraine 7renvoie 0
strings.IndexRune(string,char)Allerrenvoie −1
string.indexOf(char«,startpos»)Java , JavaScriptrenvoie −1
string.IndexOf(char«,startpos«, charcount»»)VB .NET , C# , Windows PowerShell , F#renvoie −1
(position charstring)Common Lisprenvoie NILISLISPrenvoie nulHaskell (retourne )Just indexne renvoie rienOCamlLève une exception Not_found[a]Fortranrenvoie zéro
string indexOf: char ifAbsent: aBlockstring indexOf: charstring includes: charConversationévaluer aBlockqui est un BlockClosure(ou tout objet comprenant la valeur) renvoie 0 renvoie trueoufalse
index(string, char, startpos )PL/I renvoie 0 (les positions commencent à 1)
string.index(?char)Rubisrenvoie nulPHPrenvoie fauxCobrarenvoie −1
stringcharAPLrenvoie 1 + la dernière position dans la chaîne
string.find(substring)Rouille renvoie Aucun.IndexOf ( 'e' ); // renvoie 1 "word" .IndexOf ( ' z' ) // renvoie -1
) ; renvoie 1 ( position #\z "word" ) ; renvoie NIL

^a Étant donné un ensemble de caractères, SCAN renvoie la position du premier caractère trouvé, tandis que VERIFY renvoie la position du premier caractère qui n'appartient pas à l'ensemble.

Format

Définitionformat(formatstring, items)renvoie une chaîne de caractères
DescriptionRenvoie la représentation sous forme de chaîne formatée d'un ou plusieurs éléments.
FormatLanguesSyntaxe de la chaîne de formatage
associate(file, string); ALGOL 68ALGOL
Format(item, formatstring)VB
sprintf(formatstring, items)Perl , PHP , Raku , RubyC
item.fmt(formatstring)RakuC
io_lib:format(formatstring, items)Erlang
sprintf(outputstring, formatstring, items)CC
std::format(formatstring, items)C++ ( C++20 )Python
std.string.format(formatstring, items)DC
Format(formatstring, items)Objet Pascal ( Delphi )
fmt.Sprintf(formatstring, items)AllerC
printfformatstringitemsUnixC
formatstring% (items)Python , RubyC
formatstring.format(items)Python.FILET
fformatstringPython 3
Printf.sprintf formatstringitemsOCaml , F#C
Text.Printf.printf formatstringitemsHaskell ( GHC )C
formatstring printf: itemsConversationC
String.format(formatstring, items)JavaC
String.Format(formatstring, items)VB .NET , C# , F#.FILET
(format formatstringitems)Schéma (SRFI 28)Zézayer
(format nil formatstringitems)Common LispZézayer
(format formatstringitems)ClojureZézayer
formatstring -f itemsWindows PowerShell.FILET
[NSString stringWithFormat:formatstring, items]Objectif-C ( NSString *uniquement)C
String(format:formatstring, items)Swift (Fondation)C
string.format(formatstring, items)(formatstring):format(items)LuaC
WRITE (outputstring, formatstring) itemsFortranFortran
put string(string) edit(items)(format)PL/IPL/I (similaire à Fortran)
String.format(formatstring, items)Cobra.FILET
format formatstring itemsTclC
formatnumbersitemsformatstring ⎕FMT itemsAPLAPL
format!(formatstring, items)Rouille Python
Mon {0} coûte {1:C2}" , "stylo" , 19.99 ); // renvoie "Mon stylo coûte 19,99 $"
, " stylo" , 19.99 ); // renvoie "Mon stylo coûte 19,99 $"
, "stylo", 19.99 ; # renvoie "Mon stylo coûte 19,99 $" 1.fmt ( " % 04d " ) ; # renvoie " 0001 "
%s coûte %.2f $ " % ( "stylo" , 19.99 ); # renvoie "Mon stylo coûte 19,99 $" "Mon {0} coûte {1:.2f} $ " . format ( "stylo" , 19.99 ); # renvoie "Mon stylo coûte 19,99 $"
f "Mon { pen } coûte { 19.99 } " #renvoie "Mon stylo coûte 19.99"
"stylo" 19,99 ) ; renvoie "Mon stylo coûte 19,99 $"

Inégalité

Vérifie si deux chaînes de caractères sont différentes. Voir aussi #Égalité .

FormatLangues
string1nestring2string1 NE string2ALGOL 68 – L’opérateur « ne » apparaît en caractères gras .
string1 /= string2ALGOL 68 , Ada , Erlang , Fortran , Haskell
string1 <> string2BASIC , VB , VB.NET , Pascal , Object Pascal ( Delphi ), OCaml , PHP , Seed7 , Standard ML , F# , COBOL , Cobra , Python 2 (obsolète)
string1 # string2BASIC (certaines implémentations)
string1 ne string2Perl , Raku
(string<> string1string2)Schéma (SRFI 13)
(string/= string1string2)Common Lisp
(string/= string1string2)ISLISP
(not= string1string2)Clojure
string1!= string2C++ (STL), C# , Go , JavaScript (non similaire), PHP (non similaire), Python , Ruby , Rust , Swift , D , Mathematica
string1!== string2JavaScript , PHP
string1 \= string2Rexx
string1 ¬= string2PL/I
test string1!= string2[ string1!= string2 ]Bourne Shell
string1 -ne string2Windows PowerShell
string1 ~= string2Lua , Smalltalk
string1string2APL
string1.ne(string2)Rouille
!= "world" // renvoie vrai
"world" ) ; ⇒ vrai
#Trouver

index de

voir #Trouver

instr

voir #Trouver

instrrev

voir #rfind

rejoindre

Définition join(separator, list_of_strings)renvoie une liste de chaînes de caractères reliées par un séparateur.
DescriptionConcatène la liste de chaînes de caractères en une nouvelle chaîne, en insérant la chaîne de séparation entre chaque sous-chaîne. Contraire de split .
En rapportsprintf
FormatLangues
std.string.join(array_of_strings, separator)D
string:join(list_of_strings, separator)Erlang
join(separator, list_of_strings)Perl , PHP , Raku
implode(separator, array_of_strings)PHP
separator.join(sequence_of_strings)Python , Swift 1.x
array_of_strings.join(separator)Ruby , JavaScript , Raku , Rust
(string-join array_of_stringsseparator)Schéma (SRFI 13)
(format nil "~{~a~^separator~}" array_of_strings)Common Lisp
(clojure.string/join separatorlist_of_strings)(apply str (interpose separatorlist_of_strings))Clojure
strings.Join(array_of_strings, separator)Aller
join(array_of_strings, separator)Graine 7
String.concat separatorlist_of_stringsOCaml
String.concatWith separatorlist_of_stringsML standard
Data.List.intercalate separatorlist_of_stringsHaskell ( GHC 6.8+)
Join(array_of_strings, separator)VB
String.Join(separator, array_of_strings)VB .NET , C# , F#
String.join(separator, array_of_strings)Java 8+
&{$OFS=$separator; "$array_of_strings"}array_of_strings -join separatorWindows PowerShell
[array_of_strings componentsJoinedByString:separator]Objectif-C ( NSString *uniquement)
table.concat(table_of_strings, separator)Lua
Conversation informelle ( Squeak , Pharo )
array_of_strings.join(separator«, final_separator»)Cobra
sequence_of_strings.joinWithSeparator(separator)Swift 2.x
1↓∊separatorlist_of_stringsAPL
, { "a" , " b" , "c" }) // "abc"
#( 'a' 'b' 'c' ) joinUsing: '-' " 'abc' "
. join ([ "a" , "b" , "c" ]) # 'abc'
, "b" , "c" ] .join ( "-" ) # 'abc'
"b" "c" ) "-" ) ; "abc"

dernier index de

voir #rfind

gauche

Définitionleft(string,n)renvoie une chaîne de caractères
DescriptionRenvoie les n premiers caractères d'une chaîne. Si n est supérieur à la longueur de la chaîne, la plupart des implémentations renvoient la chaîne entière (des exceptions existent – ​​voir les exemples de code). Pour les encodages à longueur variable tels que UTF-8 , UTF-16 ou Shift-JIS , il peut être nécessaire de supprimer les caractères à la fin de la chaîne afin d'éviter les chaînes invalides.
FormatLangues
Ada
substr(string, 0, n)AWK (modifie les chaînes de caractères), Perl , PHP , Raku
LEFT$(string,n)BASIC , VB
left(string,n)VB , FreeBASIC , Ingres , Pick Basic
strncpy(string2, string, n)bibliothèque standard C
string.substr(0,n)C++ (STL), Raku
[string substringToIndex:n]Objectif-C ( NSString *uniquement)
Clojure
string[0 .. n]D
string:substr(string, start, length)Erlang
(subseq string 0 n)Common Lisp
string[:n]Cobra , Go , Python
left(string,n «,padchar»)Rexx , Erlang
string[0, n]string[0..n - 1]Rubis
string[1, n]Choisissez Basique
string[ .. n]Graine 7
string.Substring(0,n)VB .NET , C# , Windows PowerShell , F#
leftstr(string, n)Pascal , Objet Pascal ( Delphi )
copy (string,1,n)Turbo Pascal
string.substring(0,n)Java , JavaScript
(string-take stringn)Schéma (SRFI 13)
take nstringHaskell
String.extract (string, n, NONE)ML standard
String.sub string 0 nOCaml
string.[..n]Fa#
string.sub(string, 1, n)(string):sub(1, n)Lua
string first: nConversation informelle ( Squeak , Pharo )
string(:n)Fortran
StringTake[string, n]Mathematica
string («FUNCTION» LENGTH(string) - n:n)COBOL
string.substring(0, n)Cobra
nstring.APL
string[0..n]string[..n]string.get(0..n)string.get(..n)Rouille
. substr ( 0 , 6 ); # renvoie "Bonjour,"
, 3 ) /* renvoie "abc" */ left ( "abcde" , 8 ) /* renvoie "abcde" */ left ( "abcde" , 8 , "*" ) /* renvoie "abcde***" */
, 3 ) ; retourne "abc" ( string-take "abcde" , 8 ) ; erreur
, 3 ) ' renvoie "san" Left ( "sandroguidi" , 100 ) ' renvoie "sandroguidi"

len

voir #longueur

longueur

Définitionlength(string)renvoie un nombre entier
DescriptionRenvoie la longueur d'une chaîne (sans compter le caractère nul de fin de chaîne ni aucune autre information structurelle interne). Une chaîne vide renvoie une longueur de 0.
FormatRetoursLangues
string'LengthAda
UPB stringALGOL 68
echo "${#string_param}"Frapper
length(string)Ingres , Perl 5, Pascal , Object Pascal ( Delphi ), Rexx , Seed7 , SQL , PL/I
len(string)BASIC , FreeBASIC , Python , Go , Choisir Basic
length(string), string:len(string)Erlang
Len(string)VB , Choisissez Basique
string.LengthNombre d' unités de code UTF-16VB .NET , C# , Windows PowerShell , F#
chars(string)string.charsNombre de graphèmes (NFG)Raku
codes(string)string.codesNombre de points de code UnicodeRaku
string.size OR string.lengthNombre d'octets Rubis
strlen(string)Nombre d'octetsC , PHP
string.length()C++ (STL)
string.lengthCobra , D , JavaScript
string.length()Nombre d' unités de code UTF-16Java
(string-length string)Schème
(length string)Common Lisp , ISLISP
(count string)Clojure
String.length stringOCaml
size stringML standard
length stringNombre de points de code UnicodeHaskell
string.lengthNombre d' unités de code UTF-16Objectif-C ( NSString *uniquement)
string.characters.countNombre de caractèresSwift (2.x)
count(string)Nombre de caractèresSwift (1.2)
countElements(string)Nombre de caractèresSwift (1.0–1.1)
string.len(string)(string):len()#stringLua
string sizeConversation
LEN(string)LEN_TRIM(string)Fortran
StringLength[string]Mathematica
«FUNCTION» LENGTH(string)ou

«FUNCTION» BYTE-LENGTH(string)

nombre de caractères et nombre d'octets, respectivementCOBOL
string length stringune chaîne décimale indiquant le nombre de caractèresTcl
stringAPL
string.len()Nombre d'octetsRouille
string.chars().count()Nombre de points de code UnicodeRouille
.Length ; // renvoie 5 " " .Length ; // renvoie 0
). % renvoie 5 chaîne : len ( ). % renvoie 0
); # renvoie 5 longueur ( ); # renvoie 0
) ' renvoie 5 Len ( ) ' renvoie 0
Longueur ] //renvoie 5 [ @"" Longueur ] //renvoie 0
#Trouver

Minuscule

Définitionlowercase(string)renvoie une chaîne de caractères
DescriptionRenvoie la chaîne en minuscules.
FormatLangues
LCase(string)VB
lcase(string)FreeBASIC
lc(string)Perl , Raku
string.lcRaku
tolower(char)C
std.string.toLower(string)D
transform(string.begin(), string.end(), result.begin(),::tolower)C++
lowercase(string)Objet Pascal ( Delphi )
strtolower(string)PHP
lower(string)Graine 7
${string_param,,}Frapper
echo "string" |tr 'A-Z' 'a-z'Unix
string.lower()Python
downcase(string)Choisissez Basique
string.downcaseRubis
strings.ToLower(string)Aller
(string-downcase string)Schéma (R6RS), Common Lisp
(lower-case string)Clojure
String.lowercase stringOCaml
String.map Char.toLower stringML standard
map Char.toLower stringHaskell
string.toLowerCase()Java , JavaScript
to_lower(string)Erlang
string.ToLower()VB .NET , C# , Windows PowerShell , F#
string.lowercaseStringObjective-C ( NSString *uniquement), Swift (Foundation)
string.lower(string)(string):lower()Lua
string asLowercaseConversation
LOWER(string)SQL
lowercase(string)PL/I
ToLowerCase[string]Mathematica
«FUNCTION» LOWER-CASE(string)COBOL
string.toLowerCobra
string tolower stringTcl
string.to_lowercase()Rouille
. ToLower (); // "wiki signifie rapide ?"
) ; "wiki signifie rapide ?"
; for ( int i = 0 ; i < sizeof ( s ) - 1 ; ++ i ) { // transformer les caractères sur place, un par un s [ i ] = tolower ( s [ i ]); } printf ( string ); // "wiki signifie rapide ?" return 0 ; }
#substring

partition

Définition<string>.partition( separator ) renvoie la sous-chaîne avant le séparateur ; le séparateur ; puis la sous-chaîne après le séparateur.
DescriptionDivise la chaîne donnée en fonction du séparateur et renvoie les trois sous-chaînes qui, ensemble, constituent la chaîne originale.
FormatLanguesCommentaires
string.partition(separator)Python , Ruby (1.9+)
lists:partition(pred, string)Erlang
split /(separator)/, string, 2Perl 5
split separator, string, 2string.split( separator, 2 )RakuLe séparateur ne doit pas nécessairement être une expression régulière.
.partition ( 'spam' ) # ('Spam eggs ', 'spam', ' spam and ham') "Spam eggs spam spam and ham" .partition ( 'X' ) # ('Spam eggs spam spam and ham', "", "")
Définitionreplace(string, find, replace)renvoie une chaîne de caractèresDescriptionRenvoie une chaîne de caractères où les occurrences de recherche ont été modifiées pour remplacer .
FormatLangues
changestr(find, string, replace)Rexx
std.string.replace(string, find, replace)D
Replace(string, find, replace)VB
replace(string, find, replace)Graine 7
change(string, find, replace)Choisissez Basique
string.Replace(find, replace)C# , F# , VB .NET
str_replace(find, replace, string)PHP
re:replace(string, find, replace, «{return, list}»)Erlang
string.replace(find, replace)Cobra , Java (1.5+), Python , Rust
string.replaceAll(find_regex, replace)Java
string.gsub(find, replace)Rubis
string =~ s/find_regex/replace/gPerl 5
string.subst(find, replace, :g)Raku
string.replace(find, replace, "g") string.replace(/find_regex/g, replace)JavaScript
echo "string" |sed 's/find_regex/replace/g'Unix
${string_param//find_pattern/replace}Frapper
string.replace(find, replace)string -replace find_regex, replaceWindows PowerShell
Str.global_replace (Str.regexp_string find) replacestringOCaml
[string stringByReplacingOccurrencesOfString:find withString:replace]Objectif-C ( NSString *uniquement)
string.stringByReplacingOccurrencesOfString(find, withString:replace)Swift (Fondation)
string.gsub(string, find, replace)(string):gsub(find, replace)Lua
string copyReplaceAll: find with: replaceConversation informelle ( Squeak , Pharo )
string map {findreplace} stringTcl
StringReplace[string, find -> replace]Mathematica
strings.Replace(string, find, replace, -1)Aller
INSPECT string REPLACING ALL/LEADING/FIRST find BY replaceCOBOL
find_regex ⎕R replace_regexstringAPL
.Replace ( " f" , "jump" ); // renvoie "ejumpjumpjumpjumpjumpjump" "blah" .Replace ( " z" , "y" ); // renvoie "blah"
.replace ( " f" , "jump" ); // renvoie "ejumpjumpjumpjumpjumpjump" "effffff" .replaceAll ( "f*" , " jump" ); // renvoie "ejump"
.subst ( "f" , "jump" , : g ); # renvoie "ejumpjumpjumpjumpjumpjump" "blah" .subst ( " z" , "y" , : g ) ; # renvoie "blah"
, "f" , "jump" ) ' renvoie "ejumpjumpjumpjumpjump" Replace ( "blah" , "z" , "y" ) ' renvoie "blah"
-replace "f" , "jump" # renvoie "ejumpjumpjumpjumpjump" "effffff -replace "f*" , "jump" # renvoie "ejump"

inverse

Définitionreverse(string)
DescriptionInverse l'ordre des caractères dans la chaîne.
FormatLangues
reverse stringPerl 5, Haskell
flip stringstring.flipRaku
lists:reverse(string)Erlang
strrev(string)PHP
string[::-1]Python
(string-reverse string)Schéma (SRFI 13)
(reverse string)Common Lisp
string.reverseRuby , D (modifie la chaîne)
new StringBuilder(string).reverse().toString()Java
std::reverse(string.begin(), string.end());C++ ( std::stringmodifie uniquement la chaîne)
StrReverse(string)VB
string.Reverse()VB .NET , C#
implode (rev (explode string))ML standard
stringJavaScript
string.reverse(string)(string):reverse()Lua
string reverseConversation
StringReverse[string]Mathematica
reverse(string)PL/I
COBOL
string.toCharArray.toList.reversed.join()Cobra
String(string.characters.reverse())Swift (2.x)
String(reverse(string))Swift (1.2)
string reverse stringTcl
stringAPL
stringRouille
echo string| revUnix
'hello' inversé " renvoie 'oleh' "
# renvoie "olleh"
[:: - 1 ] # renvoie "olleh"
) ; renvoie "olleh"

rfind

Définitionrfind(string,substring)renvoie un entier
DescriptionRenvoie la position du début de la dernière occurrence de la sous-chaîne dans la chaîne . Si la sous-chaîne est introuvable, la plupart de ces routines renvoient une valeur d'index invalide – -1 lorsque les index commencent à 0, 0 lorsqu'ils commencent à 1 – ou une valeur à interpréter comme FAUX.
En rapportinstr
FormatLanguesSi introuvable
InStrRev(«startposstring,substring)VBrenvoie 0
instrrev(«startposstring,substring)FreeBASICrenvoie 0
rindex(string,substring«,startpos»)Perl 5renvoie −1
rindex(string,substring«,startpos»)string.rindex(substring«,startpos»)Rakurenvoie NulPHPrenvoie FAUXC++ (STL)renvoie std::string::nposDrenvoie −1
string.rfind(substring«,startpos«, endpos»»)Pythonrenvoie −1
string.rindex(substring«,startpos«, endpos»»)génère une erreur de valeurGraine 7renvoie 0
string.rindex(substring«,startpos»)Rubisrenvoie nulAllerrenvoie −1
string.lastIndexOf(substring«,startpos»)Java , JavaScriptrenvoie −1
string.LastIndexOf(substring«,startpos«, charcount»»)VB .NET , C# , Windows PowerShell , F#renvoie −1
(search substringstring :from-end t)Common Lispreturns Objective-C (NSString * only)returns OCamlraises Luareturns Adareturns 0
string.lastIndexOf(substring«,startpos«, charcount»»)Cobrareturns −1
string lastIndexOfString:substringSmalltalkreturns 0
string last substring string startposTclreturns −1
APLreturns −1
string.rfind(substring)Rustreturns "Hello mate":from-endt); returns 9(search"z""word":from-endt); returns NIL
.LastIndexOf("e");// returns 9"Hello mate".LastIndexOf("e",4);// returns 1"word".LastIndexOf("z");// returns -1
,"e");# returns 9rindex("Hello mate","e",4);# returns 1rindex("word","z");# returns -1
.rindex("e"); # returns 9"Hello mate".rindex("e", 4); # returns 1"word".rindex('z'); # returns Nil
,"e")' returns 10InStrRev(5,"Hello mate","e")' returns 2InStrRev("word","z")' returns 0

right

Definitionright(string,n) returns string
DescriptionReturns the right n part of a string. If n is greater than the length of the string then most implementations return the whole string (exceptions exist – see code examples).
FormatLanguages
Ada
Right(string,n)VB
RIGHT$(string,n)BASIC
right(string,n)FreeBASIC, Ingres, Pick Basic
strcpy(string2, string+n) (C
string.Substring(string.Length()-n)C#
string[len(string)-n:]Go
string.substring(string.length()-n)Java
string.slice(-n)JavaScript
right(string,n «,padchar»)Rexx, Erlang
substr(string,-n)Perl 5, PHP
substr(string,*-n)string.substr(*-n)Raku
string[-n:]Cobra, Python
${string_param: -n} (a space occurs after the colon)Bash
string[n]Pick Basic
(string-take-right stringn)Scheme (SRFI 13)
string[-n..-1]Ruby
string[$-n .. $]D
String.sub string (String.length string - n) nOCaml
string.sub(string, -n)(string):sub(-n)Lua
string last: nSmalltalk (Squeak, Pharo)
StringTake[string, -n]Mathematica
string (1:n)COBOL
¯nstring.APL
string[n..]string.get(n..)Rust
;str.substring(str.length()-4);// returns 'Door'
.substr(*-3); # returns "cde""abcde".substr(*-8); # 'out of range' error
,3)/* returns "cde" */right("abcde",8)/* returns " abcde" */right("abcde",8,"*")/* returns "***abcde" */
,3); returns "cde"(string-take-right"abcde",8); error
,3)' returns "idi"Right("sandroguidi",100)' returns "sandroguidi"

rpartition

Definition<string>.rpartition(separator) Searches for the separator from right-to-left within the string then returns the sub-string before the separator; the separator; then the sub-string after the separator.
DescriptionSplits the given string by the right-most separator and returns the three substrings that together make the original.
FormatLanguages
string.rpartition(separator)Python, Ruby
.rpartition('spam')### ('Spam eggs spam ', 'spam', ' and ham')"Spam eggs spam spam and ham".rpartition('X')### ("", "", 'Spam eggs spam spam and ham')

slice

see#substring

split

Definition<string>.split(separator[, limit]) splits a string on separator, optionally only up to a limited number of substrings
DescriptionSplits the given string by occurrences of the separator (itself a string) and returns a list (or array) of the substrings. If limit is given, after limit – 1 separators have been read, the rest of the string is made into the last substring, regardless of whether it has any separators in it. The Scheme and Erlang implementations are similar but differ in several ways. JavaScript differs also in that it cuts, it does not put the rest of the string into the last element. See the example here. The Cobra implementation will default to whitespace. Opposite of join.
FormatLanguages
split(/separator/, string«, limit»)Perl 5
split(separator, string«, limit»)string.split(separator, «limit»)Raku
explode(separator, string«, limit»)PHP
string.split(separator«, limit-1»)Python
string.split(separator«, limit»)JavaScript, Java, Ruby
string:tokens(string, sepchars)Erlang
strings.Split(string, separator)strings.SplitN(string, separator, limit)Go
(string-tokenize string«charset«start«end»»»)Scheme (SRFI 13)
Split(string, sepchars«, limit»)VB
string.Split(sepchars«, limit«, options»»)VB .NET, C#, F#
string -split separator«, limit«, options»»Windows PowerShell
Str.split (Str.regexp_string separator) stringOCaml
std.string.split(string, separator)D
[string componentsSeparatedByString:separator]Objective-C (NSString * only)
string.componentsSeparatedByString(separator)Swift (Foundation)
TStringList.Delimiter, TStringList.DelimitedTextObject Pascal
StringSplit[string, separator«, limit»]Mathematica
string.split«(sepchars«, limit«, options»»)»Cobra
split string separatorTcl
(separatorstring)⊂string in APL2separator(≠⊆⊢)string in Dyalog APL 16.0APL
string.split(separator)

string.split(limit, separator)

Rust
.Split(',');// {"abc", "defgh", "ijk"}"abc,defgh;ijk".Split(',',';');// {"abc", "defgh", "ijk"}
,";").% ["abc", "defgh", "ijk"]
.split(",");// {"abc", "defgh", "ijk"}"abc,defgh;ijk".split(",|;");// {"abc", "defgh", "ijk"}
#Format

strip

see#trim

strcmp

see#Compare (integer result)

substring

Definitionsubstring(string, startpos, endpos) returns stringsubstr(string, startpos, numChars) returns string
DescriptionReturns a substring of string between starting at startpos and endpos, or starting at startpos of length numChars. The resulting string is truncated if there are fewer than numChars characters beyond the starting point. endpos represents the index after the last character in the substring. 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.
FormatLanguages
string[startpos:endpos]ALGOL 68 (changes base index)
string (startpos .. endpos)Ada (changes base index)
Mid(string, startpos, numChars)VB
mid(string, startpos, numChars)FreeBASIC
string[startpos+(⍳numChars)-~⎕IO]APL
MID$(string, startpos, numChars)BASIC
substr(string, startpos, numChars)AWK (changes string), Perl 5,PHP
substr(string, startpos, numChars)string.substr(startpos, numChars)Raku
substr(string, startpos «,numChars, padChar»)PL/I
substr(string, startpos «,numChars, padChar»)Rexx
string[startpos:endpos]Cobra, Python,Go
string[startpos, numChars]Pick Basic
string[startpos, numChars]string[startpos .. endpos-1]string[startpos ... endpos]Ruby
string[startpos .. endpos]string[startpos len numChars]Seed7
string.slice(startpos«, endpos»)JavaScript
string.substr(startpos«, numChars»)C++ (STL), JavaScript
string.Substring(startpos, numChars)VB .NET, C#, Windows PowerShell, F#
string.substring(startpos«, endpos»)Java, JavaScript
copy(string, startpos, numChars)Object Pascal (Delphi)
(substring stringstartposendpos)Scheme
(subseq stringstartposendpos)Common Lisp
(subseq stringstartposendpos)ISLISP
String.sub stringstartposnumCharsOCaml
substring (string, startpos, numChars)Standard ML
string:sub_string(string, startpos, endpos)string:substr(string, startpos, numChars)Erlang
strncpy(result, string + startpos, numChars);C
string[startpos .. endpos+1]D
take numChars $ drop startposstringHaskell
[string substringWithRange:NSMakeRange(startpos, numChars)]Objective-C (NSString * only)
string.[startpos..endpos]F#
string.sub(string, startpos, endpos)(string):sub(startpos, endpos)Lua
string copyFrom: startpos to: endposSmalltalk
string(startpos:endpos)Fortran
SUBSTRING(string FROM startpos «FOR numChars»)SQL
StringTake[string, {startpos, endpos}]Mathematica
string (startpos:numChars)COBOL
${string_param:startpos:numChars}Bash
string range string startpos endposTcl
string[startpos..endpos]string.get(startpos..endpos)Rust
.Substring(1,1):// returns "b""abc".Substring(1,2);// returns "bc""abc".Substring(1,6);// error
12); returns "b"(subseq"abc"2); returns "c"
,2,1).% returns "b"string:substr("abc",2).% returns "bc"
,1,1);# returns "b"substr("abc",1);# returns "bc"
.substr(1, 1); # returns "b""abc".substr(1); # returns "bc"
[1:2]# returns "b""abc"[1:3]# returns "bc"
,2,1)/* returns "b" */substr("abc",2)/* returns "bc" */substr("abc",2,6)/* returns "bc " */substr("abc",2,6,"*")/* returns "bc****" */

Uppercase

Definitionuppercase(string) returns string
DescriptionReturns the string in upper case.
FormatLanguages
UCase(string)VB
ucase(string)FreeBASIC
toupper(string)AWK (changes string)
uc(string)Perl, Raku
string.ucRaku
toupper(char)C (operates on one character)
C (string / char array)
std.string.toUpper(string)D
transform(string.begin(), string.end(), result.begin(), toupper)C++
uppercase(string)Object Pascal (Delphi)
upcase(char)Object Pascal (Delphi) (operates on one character)
strtoupper(string)PHP
upper(string)Seed7
${string_param^^} (mnemonic: ^ is pointing up)Bash
echo "string" |tr 'a-z' 'A-Z'Unix
translate(string)UPPER variablesRexx
string.upper()Python
upcase(string)Pick Basic
string.upcaseRuby
strings.ToUpper(string)Go
(string-upcase string)Scheme, Common Lisp
String.uppercase stringOCaml
String.map Char.toUpper stringStandard ML
map Char.toUpper stringHaskell
string.toUpperCase()Java, JavaScript
string.uppercase()Kotlin
to_upper(string)Erlang
string.ToUpper()VB .NET, C#, Windows PowerShell, F#
string.uppercaseStringObjective-C (NSString * only), Swift (Foundation)
string.upper(string)(string):upper()Lua
string asUppercaseSmalltalk
UPPER(string)SQL
ToUpperCase[string]Mathematica
COBOL
string.toUpperCobra
string toupper stringTcl
string.to_uppercase()Rust
.ToUpper();// "WIKI MEANS FAST?"
);# "WIKI MEANS FAST?"
); # "WIKI MEANS FAST?""Wiki means fast?".uc; # "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." */
); "WIKI MEANS FAST?"
)' "WIKI MEANS FAST?"

trim

Example usageLanguagesString.Trim([chars])C#, VB.NET, Windows PowerShellstring.strip();D(.trim string)Clojuresequence [ predicate? ] trimFactorCommon Lisp(string-trim string)Schemestring.trim()Java, JavaScript (1.8.1+, Firefox 3.5+), RustTrim(String)Pascal,QBasic, Visual Basic, Delphistring.strip()Pythonstrings.Trim(string, chars)GoLTRIM(RTRIM(String))OracleSQL, T-SQLstrip(string [,option, char])REXXstring:strip(string [,option, char])Erlangstring.stripstring.lstripstring.rstripRubystring.trimRakutrim(string)PHP, Raku[stringObjective-C using Cocoastring withBlanksTrimmedstring withoutSpacesstring withoutSeparatorsSmalltalk (Squeak, Pharo)Smalltalkstrip(string)SASstring trim $stringTclTRIM(string)TRIM(ADJUSTL(string))FortranTRIM(string)SQLTRIM(string)LTrim(string)RTrim(String)ColdFusionString.trim stringOCaml 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:

AWK, one can use regular expressions to trim:

open source C++ library Boost has several trim variants, including a standard one:

);

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:

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.

Haskell

A trim algorithm in Haskell:

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

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

J

The trim algorithm in J is a functional description:

regular expressions.

Example:

CPAN.

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

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

In Raku, the upcoming sister language of Perl, strings have a trim method.

Example:

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:

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:

Plus d articles de Worldlex Wiki

Revenez a l index pour explorer davantage de pages sur l histoire, la science, la culture, la geographie et la societe en francais.

Explorer l index