文字列関数は、コンピュータプログラミング言語において、文字列を操作したり、文字列に関する情報を照会したりするために使用されます(両方の機能を持つものもあります)。
文字列データ型を持つほとんどのプログラミング言語には、文字列関数が用意されていますが、各言語内には文字列を直接扱うための低レベルな方法も存在する場合があります。オブジェクト指向言語では、文字列関数は文字列オブジェクトのプロパティやメソッドとして実装されることがよくあります。関数型言語やリストベースの言語では、文字列は(文字コードのリストとして)表現されるため、リスト操作の手順はすべて文字列関数とみなすことができます。ただし、これらの言語でも、文字列専用の明示的な関数が別途実装されている場合があります。
文字列を操作する関数に関して、 C#やJavaのような最新のオブジェクト指向言語では、文字列は不変であり、(新しく割り当てられた動的メモリに)コピーを返します。一方、C言語のような他の言語では、プログラマがデータを新しい文字列にコピーしない限り、元の文字列が操作されます。例えば、以下の文字列連結を参照してください。
文字列関数の最も基本的な例は、関数です。この関数は、文字列リテラルlength(string)の長さを返します。
length("hello world")11が返されます。他の言語にも、構文や引数、結果が似ている、あるいは全く同じ文字列関数が存在する場合があります。例えば、多くの言語では長さ関数は通常len(string)と表記されます。以下に、よく使われる関数の一覧を示します。これは、こうした混乱を軽減することを目的としています。
多くの言語で共通する文字列関数を、使用されているさまざまな名前を含めて以下に示します。以下の共通関数のリストは、プログラマーが言語内で同等の関数を見つけるのに役立つことを目的としています。文字列連結と正規表現は別のページで扱います。ギユメ(« … »)で囲まれたステートメントは省略可能です。[ 1 ]
{ Pascal の例 } var MyStr : string = 'Hello, World' ; MyChar : Char ; begin MyChar := MyStr [ 2 ] ; // 'e'# ALGOL 68 の例 # "こんにちは、世界"[2]; // 'e'
// C言語の例#include <stdio.h>char myStr1 [] = "Hello, World" ; printf ( "%c" , * ( myStr1 + 1 )); // 'e' printf ( "%c" , * ( myStr1 + 7 )); // 'W' printf ( "%c" , myStr1 [ 11 ]); // 'd' printf ( "%s" , myStr1 ); // 'Hello, World' printf ( "%s" , "Hello(2), World(2)" ); // 'Hello(2), World(2)'import std ;std :: stringを使用します。char myStr1 [] = "Hello(1), World(1)" ; string myStr2 = "Hello(2), World(2)" ; std :: println ( "Hello(3), World(3)" ); // 'Hello(3), World(3)' std :: println ( "{}" , myStr2 [ 6 ]); // '2' std :: println ( "{}" , myStr1 . substr ( 5 , 3 )); // '(1)'// C# の例"Hello, World" [ 2 ]; // 'l'# Perl 5 の例substr ( "Hello, World" , 1 , 1 ); # 'e'# Python の例"Hello, World" [ 2 ] # 'l' "Hello, World" [ - 3 ] # 'r'# Raku の例"Hello, World" . substr ( 1 , 1 ); # 'e'' Visual Basic の例Mid ( "Hello, World" , 2 , 1 )' Visual Basic .NET の例"Hello, World" . Chars ( 2 ) ' "l"c「Smalltalkの例」「Hello, World」at: 2 . "$e"//Rustの例"Hello, World" . chars (). nth ( 2 ); // Some('l')# Perl 5 の例"hello" cmp "world" ; # -1 を返します# Pythonの例cmp ( "hello" , "world" ) # -1を返す# Rakuの例"hello" cmp "world" ; # Lessを返す"world" cmp "hello" ; # Moreを返す"hello" cmp "hello" ; # Sameを返す/** Rexx の例 */ compare ( "hello" , "world" ) /* 不一致のインデックスを返します: 1 */; Scheme の例( use-modules ( srfi srfi-13 )) ; 不一致のインデックスを返します: 0 ( string-compare "hello" "world" values values values )% Erlangの例"hello" > "world" . % falseを返します# 楽焼の例"art" gt "painting" ; # False を返す"art" lt "painting" ; # True を返す# Windows PowerShell の例"hello" -gt "world" # false を返します;; Common Lisp の例( string> "art" "painting" ) ; nil を返します( string< "art" "painting" ) ; nil 以外を返します{ Pascalの例 } 'abc' + 'def' ; // "abcdef" を返します// C# の例"abc" + "def" ; // "abcdef" を返します' Visual Basic の例"abc" & "def" ' "abcdef" を返します " abc" + "def" ' "abcdef" を返します " abc" & Null ' "abc" を返します " abc" + Null ' Null を返します// D言語の例"abc" ~ "def" ; // "abcdef" を返します;; Common Lisp の例( concatenate 'string "abc " "def " "ghi" ) ; "abc def ghi" を返します# Perl 5 の例"abc" . "def" ; # "abcdef" を返します"Perl " . 5 ; # "Perl 5" を返します/* PL/I の例 */ "abc" || "def" /* "abcdef" を返します */# Raku の例"abc" ~ "def" ; # "abcdef" を返します"Perl " ~ 6 ; # "Perl 6" を返します/* Rexx の例 */ "Strike" 2 /* "Strike2" を返します */ "Strike" 2 /* "Strike 2" を返します */¢ ALGOL 68の例¢ string in string("e", loc int , "Hello mate"); ¢ trueを返します¢ string in string("z", loc int , "word"); ¢ falseを返します¢
// C# の例"Hello mate" . Contains ( "e" ); // true を返す"word" . Contains ( "z" ); // false を返す# Pythonの例"e" in "Hello mate" # trueを返す"z in "word" # falseを返す# Raku の例"Good morning!" . contains ( 'z' ) # False を返す"¡Buenos días!" . contains ( 'í' ); # True を返すSmalltalkの例 " 'Hello mate' includesSubstring: 'e' "はtrueを返します " ' word ' includesSubstring: 'z' "はfalseを返します "2 つの文字列が等しいかどうかをテストします。#Compareおよび#Compareも参照してください。整数結果を持つ汎用 Compare を使用して等価性チェックを行うことは、プログラマーにとって混乱を招くだけでなく、多くの場合、かなりコストのかかる操作になります。これは、「 C 文字列」を使用する場合に特に当てはまります。
// C# の例"hello" == "world" // は false を返します' Visual Basic の例"hello" = "world" ' は false を返します# Perl 5 の例'hello' eq 'world' # 0 を返す'hello' eq 'hello' # 1 を返す# Rakuの例'hello' eq 'world' # Falseを返す'hello' eq 'hello' # Trueを返す# Windows PowerShell の例"hello" -eq "world" # false を返します⍝ APLの例'hello' ≡ 'world' ⍝ 0を返します例
(検索"e" "Hello mate" ) ; 1 を返す(検索"z" "word" ) ; NIL を返す"Hello mate" . IndexOf ( "e" ); // 1 を返す"Hello mate" . IndexOf ( "e" , 4 ); // 9 を返す"word" . IndexOf ( "z" ); // -1 を返す"こんにちは!" . index ( 'e' ) # 1 を返す"こんにちは!" . index ( 'z' ) # Nil を返す( use-modules ( srfi srfi-13 )) ( string-contains "Hello mate" "e" ) ; 1 を返す( string-contains "word" "z" ) ; #f を返す' InStr ( "Hello mate" , "e" )の例' は 2 を返します。InStr ( 5 , "Hello mate" , "e" )は 10 を返します。 InStr ( "word" , "z" )は 0 を返します。「こんにちは」indexOfSubCollection: 'ate' "returns 8"「こんにちは」indexOfSubCollection: 'late' "returns 0"私は「こんにちは、相棒」indexOfSubCollection: 'late' ifAbsent: [ 99 ] "99を返します"「こんにちは」indexOfSubCollection: 'late' ifAbsent: [ self error ] "例外が発生します"// C# の例"Hello mate" . IndexOf ( 'e' ); // 1 を返す"word" . IndexOf ( 'z' ) // -1 を返す; Common Lispの例(位置#\e "Hello mate" ) ; 1を返す(位置#\z "word" ) ; NILを返す^a文字セットが与えられた場合、SCAN は最初に見つかった文字の位置を返します[ 22 ]。一方、VERIFY はセットに属さない最初の文字の位置を返します[ 23 ] 。
// C# の例String.Format ( " My {0} costs {1:C2}" , "pen" , 19.99 ); // "My pen costs $19.99" を返します// オブジェクトパスカル (Delphi)形式の例( 'My %s costs $%2f' , [ 'pen' , 1 9.99 ]) ; // "My pen costs $19.99" を返します// Javaの例String.format ( " My %s costs $%2f" , "pen" , 19.99 ); // "My pen costs $19.99" を返します# Raku の例sprintf "My %s costs \$%.2f" , "pen" , 19.99 ; # "My pen costs $19.99" を返します1 . fmt ( "%04d" ); # "0001" を返します# Python の例"My %s costs $ %.2f " % ( "pen" , 19.99 ); # "My pen costs $19.99" を返します"My {0} costs $ {1:.2f} " . format ( "pen" , 19.99 ); # "My pen costs $19.99" を返します#Python 3.6+ の例pen = "pen" f "My { pen } costs { 19.99 } " #"My pen costs 19.99" を返します; Schemeの例( format "My ~a costs $~1,2F" "pen" 19.99 ) ; "My pen costs $19.99" を返します/* PL/I の例 */ put string ( some_string ) edit ( 'My ' , 'pen' , ' costs' , 19.99 )( a , a , a , p '$$$V.99' ) /* "My pen costs $19.99" を返します */2 つの文字列が等しくないかどうかをテストします。#Equalityも参照してください。
// C# の例"hello" != "world" // true を返す' Visual Basic の例"hello" <> "world" ' は true を返します;; Clojureの例( not= "hello" "world" ) ; ⇒ true# Perl 5 の例'hello' ne 'world' # 1 を返します# Rakuの例'hello' ne 'world' # Trueを返す# Windows PowerShell の例"hello" -ne "world" # true を返します#Find を参照
#Find を参照
#Find を参照
#rfindを参照してください
// C# の例String.Join ( "-" , { "a" , " b" , "c" }) // "abc"「Smalltalkの例」#( 'a' 'b' 'c' ) joinUsing: '-' " 'abc' "# Perl 5 の例join ( '-' , ( 'a' , 'b' , 'c' )); # 'abc'# Raku の例<ab c> . join ( '-' ); # 'abc'# Python の例"-" . join ([ "a" , "b" , "c" ]) # 'abc'# Ruby の例[ "a" , "b" , "c" ]. join ( "-" ) # 'abc'; Scheme の例( use-modules ( srfi srfi-13 )) ( string-join ' ( "a" "b" "c" ) "-" ) ; "abc"#rfindを参照してください
# Raku の例"Hello, there!" . substr ( 0 , 6 ); # "Hello," を返します/* Rexx の例 */ left ( "abcde" , 3 ) /* "abc" を返します */ left ( "abcde" , 8 ) /* "abcde " を返します */ left ( "abcde" , 8 , "*" ) /* "abcde***" を返します */; Schemeの例( use-modules ( srfi srfi-13 )) ( string-take "abcde" , 3 ) ; "abc" を返します( string-take "abcde" , 8 ) ; エラー' Visual Basic の例Left ( "sandroguidi" , 3 ) ' "san" を返しますLeft ( "sandroguidi" , 100 ) ' "sandroguidi" を返します#lengthを参照してください
// C# の例"hello" . Length ; // 5 を返します"" . Length ; // 0 を返します# Erlangの例string : len ( "hello" ). % 5を返しますstring : len ( "" ). % 0を返します# Perlの例 5 length ( "hello" ); # 5を返しますlength ( "" ); # 0を返します# Raku の例"" . chars ; chars "" ; # 両方とも 0 を返します"" . codes ; codes "" ; # 両方とも 0 を返します' Visual Basic の例Len ( "hello" ) ' は 5 を返しますLen ( "" ) ' は 0 を返します//Objective-Cの例[ @"hello" Length ] //5を返します[ @"" Length ] //0を返します-- Lua の例( "hello" ): len () -- 5 を返します# "" -- 0 を返します#Find を参照
// C# の例"Wiki は速いという意味ですか? . ToLower (); // "wiki は速いという意味ですか?; Scheme の例( use-modules ( srfi srfi-13 )) ( string-downcase "Wiki は速いという意味ですか? ) ; "wiki は速いという意味ですか?/* C言語の例 */ #include <ctype.h> #include <stdio.h>int main ( void ) { char s [] = "Wikiは速いという意味ですか?" ; for ( int i = 0 ; i < sizeof ( s ) - 1 ; ++ i ) { // 文字を1文字ずつその場で変換しますs [ i ] = tolower ( s [ i ]); } printf ( string ); // "wikiは速いという意味ですか?" return 0 ; }# Rakuの例"Wikiは速いという意味ですか? . lc ; # "wikiは速いという意味ですか?#substringを参照してください
# 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', "", "")# 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');// C# の例"effffff" . Replace ( "f" , "jump" ); // "ejumpjumpjumpjumpjumpjump" を返します"blah" . Replace ( "z" , "y" ); // "blah" を返します// Java の例"effffff" . replace ( "f" , "jump" ); // "ejumpjumpjumpjumpjumpjump" を返します"effffff" . replaceAll ( "f*" , "jump" ); // "ejump" を返します// Rakuの例"effffff" . subst ( "f" , "jump" , : g ); # "ejumpjumpjumpjumpjumpjump" を返します"blah" . subst ( "z" , "y" , : g ); # "blah" を返します' Visual Basic の例Replace ( "effffff" , "f" , "jump" ) ' "ejumpjumpjumpjumpjumpjump" を返しますReplace ( "blah" , "z" , "y" ) ' "blah" を返します# Windows PowerShell の例"effffff" -replace "f" , "jump" # "ejumpjumpjumpjumpjumpjump" を返します"effffff" -replace "f*" , "jump" # "ejump" を返しますSmalltalkの例:「'hello'を逆にすると'olleh'が返される」# Perl 5 の例reverse "hello" # "olleh" が返される# Rakuの例"hello" . flip # "olleh" を返します# Pythonの例"hello" [:: - 1 ] # "olleh"を返します; Schemeの例( use-modules ( srfi srfi-13 )) ( string-reverse "hello" ) ; "olleh" を返します; Common Lisp の例( search "e" "Hello mate" :from-end t ) ; 9 を返します( search "z" "word" :from-end t ) ; NIL を返します// C# の例"Hello mate" . LastIndexOf ( "e" ); // 9 を返します"Hello mate" . LastIndexOf ( "e" , 4 ); // 1 を返します"word" . LastIndexOf ( "z" ); // -1 を返します# Perl 5 の例rindex ( "Hello mate" , "e" ); # 9 を返しますrindex ( "Hello mate" , "e" , 4 ); # 1 を返しますrindex ( "word" , "z" ); # -1 を返します# Rakuの例"Hello mate" . rindex ( "e" ); # 9 を返します"Hello mate" . rindex ( "e" , 4 ); # 1 を返します"word" . rindex ( 'z' ); # Nil を返します' Visual Basic の例InStrRev ( "Hello mate" , "e" ) ' は 10 を返しますInStrRev ( 5 , "Hello mate" , "e" ) ' は 2 を返しますInStrRev ( "word" , "z" ) ' は 0 を返します// Java の例。右端の 4 文字を抽出します。String str = "CarDoor" ; str . substring ( str . length () - 4 ); // 'Door' を返します# Rakuの例"abcde" . substr (*- 3 ); # "cde" を返す"abcde" . substr (*- 8 ); # '範囲外' エラー/* Rexx の例 */ right ( "abcde" , 3 ) /* "cde" を返します */ right ( "abcde" , 8 ) /* " abcde" を返します */ right ( "abcde" , 8 , "*" ) /* "***abcde" を返します */; Schemeの例( use-modules ( srfi srfi-13 )) ( string-take-right "abcde" , 3 ) ; "cde"を返します( string-take-right "abcde" , 8 ) ; エラー' Visual Basic の例Right ( "sandroguidi" , 3 ) ' は "idi" を返しますRight ( "sandroguidi" , 100 ) ' は "sandroguidi" を返します# 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')#substringを参照してください
// C# の例"abc,defgh,ijk" . Split ( ',' ); // {"abc", "defgh", "ijk"} "abc,defgh;ijk" . Split ( ',' , ';' ); // {"abc", "defgh", "ijk"}% Erlangの例string : tokens ( "abc;defgh;ijk" , ";" ). % ["abc", "defgh", "ijk"]// Javaの例"abc,defgh,ijk" . split ( "," ); // {"abc", "defgh", "ijk"} "abc,defgh;ijk" . split ( ",|;" ); // {"abc", "defgh", "ijk"}{ 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 ;# Perl 5 の例split ( /spam/ , 'Spam eggs spam spam and ham' ); # ('Spam eggs ', ' ', ' and ham') split ( /X/ , 'Spam eggs spam spam and ham' ); # ('Spam eggs spam spam and ham')# 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)#Formatを参照してください
#trimを参照
#Compare(整数値の結果)を参照してください
// C# の例"abc" . Substring ( 1 , 1 ): // "b" を返します"abc" . Substring ( 1 , 2 ); // "bc" を返します"abc" . Substring ( 1 , 6 ); // エラー;; Common Lisp の例( subseq "abc" 1 2 ) ; "b" を返します( subseq "abc" 2 ) ; "c" を返します% Erlangの例string : substr ( "abc" , 2 , 1 ). % "b"を返しますstring : substr ( "abc" , 2 ). % "bc"を返します# Perl 5 の例substr ( "abc" , 1 , 1 ); # "b" を返しますsubstr ( "abc" , 1 ); # "bc" を返します# Raku の例"abc" . substr ( 1 , 1 ); # "b" を返します"abc" . substr ( 1 ); # "bc" を返します# Python の例"abc" [ 1 : 2 ] # "b" を返します"abc" [ 1 : 3 ] # "bc" を返します/* Rexx の例 */ substr ( "abc" , 2 , 1 ) /* "b" を返します */ substr ( "abc" , 2 ) /* "bc" を返します */ substr ( "abc" , 2 , 6 ) /* "bc " を返します */ substr ( "abc" , 2 , 6 , "*" ) /* "bc****" を返します */// C# の例"Wiki は速いという意味ですか? . ToUpper (); // "WIKI は速いという意味ですか?# Perl 5 の例uc ( "Wiki は速いという意味ですか? ); # "WIKI は速いという意味ですか?# Raku ucの例( "Wiki は速いという意味ですか? ); # "WIKI は速いという意味ですか? "Wiki は速いという意味ですか? . uc ; # "WIKI は速いという意味ですか?/* Rexx の例 */ translate ( "Wiki は速いという意味ですか? ) / * "WIKI は速いという意味ですか? *//* 例 #2 */ A = 'これは例です。' 大文字のA /* "これは例です。" *//* 例 #3 */ A = 'Translate 関数を使用して大文字に変換します。' Translate UPPER VAR A Z /* Z="Translate 関数を使用して大文字に変換します。" */; Scheme の例( use-modules ( srfi srfi-13 )) ( string-upcase "Wiki は速いという意味ですか? ) ; "WIKI は速いという意味ですか?' Visual Basic UCaseの例( "Wiki は速いという意味ですか? ) ' "WIKI は速いという意味ですか?trimまたは、strip文字列の先頭、末尾、または先頭と末尾の両方から空白文字を削除するために使用されます。
その他の言語
組み込みのトリム関数がない言語では、同じタスクを実行するカスタム関数を作成するのは通常簡単です。
APLは正規表現を直接使用できます。
トリム← '^ +| +$' ⎕R ''あるいは、先頭と末尾の空白を除去するブールマスクを組み合わせた機能的なアプローチもあります。
トリム← { ⍵ /⍨ ( ∨ \ ∧ ∘ ⌽∨ \∘ ⌽ ) ' ' ≠ ⍵ }または、先頭のスペースを2回削除して逆方向に回す:
トリム← { ( ∨ \ ' ' ≠ ⍵ ) / ⍵ } ∘ ⌽ ⍣ 2AWKでは、正規表現を使用してトリミングできます。
ltrim ( v ) = gsub ( /^[ \t]+/ , "" , v ) rtrim ( v ) = gsub ( /[ \t]+$/ , "" , v ) trim ( v ) = ltrim ( v ); rtrim ( v )または:
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++ には標準の trim 関数はありません。C 用の利用可能な文字列ライブラリ[ 58 ]のほとんどには、トリミングを実装するコード、または効率的な実装を大幅に容易にする関数が含まれています。この関数は、一部の非標準 C ライブラリではEatWhitespaceと呼ばれることもあります。
C言語では、プログラマーはトリムを実装するためにltrimとrtrimを組み合わせることがよくあります。
#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 ); }オープンソースのC++ライブラリBoostには、標準のものを含め、いくつかのtrimバリアントがあります。[ 59 ]
#include <boost/algorithm/string/trim.hpp>trimmed = boost :: algorithm :: trim_copy ( "string" );boost の関数は単に名前が付けられており、trim入力シーケンスをその場で変更し、結果を返しません。
別のオープンソースのC++ライブラリであるQtには、標準のものを含め、いくつかのtrimバリアントがあります。[ 60 ]
#include <QString>trimmed = s.trimmed ( ) ;Linuxカーネルには、2.6.18-rc1以降、文字列を「その場で」トリミングするstrip関数も含まれていますstrstrip()。2.6.33-rc1以降、カーネルは誤った警告を避けるためstrim()に、の代わりにを使用しますstrstrip()。[ 61 ]
Haskellで記述されたトリムアルゴリズム:
import Data.Char ( isSpace ) trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace次のように解釈できます。fは直前の空白文字を削除し、文字列を反転します。その後、 fは自身の出力に再度適用されます。型シグネチャ(2 行目)は省略可能です。
Jにおけるトリムアルゴリズムは、以下の関数記述で表されます。
トリム=. #~ [: ( +./\ *. +./\. ) ' ' &~:つまり、先頭のスペースと末尾のスペースの間にある#~非スペース文字をフィルターで除去します。' '&~:+./\*.+./\.
JavaScript 1.8.1 (Firefox 3.5 以降) および ECMAScript 5 標準には、組み込みのトリム関数があります。それ以前のバージョンでは、次のように String オブジェクトのプロトタイプに追加できます。
String.prototype.trim = function ( ) { return this.replace ( /^\s+/g , "" ) .replace ( / \s+$/ g , " " ) ; } ;Perl 5には組み込みのtrim関数はありません。しかし、正規表現を使用することで同様の機能を実現できます。
例:
$string =~ s/^\s+// ; # 先頭の空白を削除$string =~ s/\s+$// ; # 末尾の空白を削除または:
$string =~ s/^\s+|\s+$//g ; # 先頭と末尾の空白文字を削除これらの例では、元の変数の値を変更します$string。
Perl 用のStripLTSpaceもCPANString::Stripから入手可能です。
ただし、文字列の末尾から空白文字を削除するためによく使用される関数が 2 つありますchomp。chop
chop文字列の最後の文字を削除して返します。chomp文字列末尾に改行文字が存在する場合、それを削除します。(改行文字の定義は、$INPUT_RECORD_SEPARATORによって異なります。)Perlの姉妹言語であるRakuでは、文字列にtrimメソッドがあります。
例:
$string = $string . trim ; # 先頭と末尾の空白を削除$string .= trim ; # 同じことTclコマンドには、関連する 3 つのサブコマンドがあります。、および。これらの各コマンドには、追加の引数を指定できます。これは 、削除する文字のセットを表す文字列です。デフォルトは空白文字 (スペース、タブ、改行、キャリッジリターン) です。stringtrimtrimrighttrimleft
母音のトリミングの例:
set string onomatopoeia set trimmed [ string trim $string aeiou ] ; # 結果は nomatop set r_trimmed [ string trimright $string aeiou ] ; # 結果は onomatop set l_trimmed [ string trimleft $string aeiou ] ; # 結果は nomatopoeiaXSLTには、先頭と末尾の空白文字を削除する機能に加え、連続する空白文字(改行を含む)を1つのスペースに置き換える機能が含まれています。normalize-space(string)
例:
<xsl:variable name= 'trimmed' > <xsl:value-of select= 'normalize-space(string)' /> </xsl:variable>XSLT 2.0には正規表現が含まれており、文字列のトリミングを行うための別のメカニズムが提供されています。
トリミングのための別のXSLTテクニックは、XPath 2.0substring()関数を利用することです。
str::charsメソッドはコード ポイントを反復処理し、std::iter::Iterator::nthイテレータのメソッドはイテレータからゼロ インデックスの n 番目の値を返しますNone。operator<=>のオーバーロードされたメソッドを返します(それ以外の場合は):、( と同じ)、または。std::strong_orderingstd::weak_orderinglessequalequivalentgreater.TRUE..FALSE.Ord::cmpのメソッド:、、またはを返します。OrderingLessEqualGreatereq, ne are implemented by the PartialEq trait, and the operators <, >, <=, >= and the methods lt, gt, le, ge are implemented by the PartialOrd trait.string1, which must have enough space to store the result+ operator is implemented by the Add trait.str::contains method.std::basic_string::contains method.str::find method.startpos is IBM extension.formatstring must be a fixed literal at compile time for it to have the correct type.std::format, which is imported by the Rust prelude so that it can be used under the name format.slice::join method.&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.str::len method.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.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);std::string only, result is stored in string result which is at least as long as string, and may or may not be string itselfstr::to_lowercase method.str::replace method.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.str::rfind method.str::split and str::rsplit methods.startpos can be negative, which indicates to start that number of places before the end of the string.numChars can be negative, which indicates to end that number of places before the end of the string.startpos can not be negative, use * - startpos to indicate to start that number of places before the end of the string.numChars can not be negative, use * - numChars to indicate to end that number of places before the end of the string.endpos can be negative, which indicates to end that number of places before the end of the string.std::string only, result is stored in string result which is at least as long as string, and may or may not be string itselfstr::to_uppercase新しく割り当てられたオブジェクトを返しますStringstr::trimメソッドは元の参照を返します&str。