文字列関数は、コンピュータプログラミング言語で文字列を操作したり、文字列に関する情報を照会したりするために使用されます (両方を行うものもあります)。
文字列データ型を持つほとんどのプログラミング言語には、いくつかの文字列関数がありますが、各言語には文字列を直接処理する他の低レベルの方法がある場合があります。オブジェクト指向言語では、文字列関数は文字列オブジェクトのプロパティとメソッドとして実装されることがよくあります。関数型言語とリストベースの言語では、文字列はリスト (文字コード) として表されるため、すべてのリスト操作手順は文字列関数と見なすことができます。ただし、このような言語では、明示的な文字列固有の関数のサブセットも実装される場合があります。
文字列を操作する関数の場合、 C#やJavaなどの最新のオブジェクト指向言語では不変の文字列があり、そのコピー (新しく割り当てられた動的メモリ内) を返します。一方、Cなどの他の言語では、プログラマーがデータを新しい文字列にコピーしない限り、元の文字列を操作します。以下の連結の例を参照してください。
文字列関数の最も基本的な例は、関数です。この関数は、文字列リテラルlength(string)の長さを返します。
- 例えば、
length("hello world")11 を返します。
他の言語には、類似またはまったく同じ構文、パラメータ、または結果を持つ文字列関数がある場合があります。たとえば、多くの言語では、長さ関数は通常len(string)と表されます。以下の一般的な関数のリストは、この混乱を抑えることを目的としています。
一般的な文字列関数(多言語リファレンス)
多くの言語に共通する文字列関数を、使用されるさまざまな名前を含めて以下にリストします。以下の共通関数のリストは、プログラマーが言語内の同等の関数を見つけるのに役立つことを目的としています。文字列の連結と正規表現は別のページで処理されることに注意してください。ギュイメット(« … ») 内のステートメントはオプションです。
キャラット
{ Pascal の例 }
var
MyStr : string = 'Hello, World' ; MyChar : Char ; begin MyChar := MyStr [ 2 ] ; // 'e'
# ALGOL 68 の例 # 「こんにちは、世界」[2]; // 'e'
// C の例
#include <stdio.h> // for printf char MyStr [] = "Hello, World" ; printf ( "%c" , * ( MyStr + 1 )); // 'e' printf ( "%c" , * ( MyStr + 7 )); // 'W' printf ( "%c" , MyStr [ 11 ]); // 'd' printf ( "%s" , MyStr ); // 'Hello, World' printf ( "%s" , "Hello(2), World(2)" ); // 'Hello(2), World(2)'
// C++ の例
#include <iostream> // "cout" 用#include <string.h> // "string" データ型用using namespace std ; char MyStr1 [] = "Hello(1), World(1)" ; string MyStr2 = "Hello(2), World(2)" ; cout << "Hello(3), World(3)" ; // 'Hello(3), World(3)' cout << MyStr2 [ 6 ]; // '2' cout << 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 を返します
# Raku の例
"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" を返します
# Raku の例
"abc" ~ "def" ; # "abcdef" を返します
"Perl " ~ 6 ; # "Perl 6" を返します
含まれるもの
¢ 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 の例
"Hello mate"の"e" # true を返す"word"の"z" # false を返す
# Raku の例
"Good morning!" . contains ( 'z' ) # False を返します
"¡Buenos días!" . contains ( 'í' ); # True を返します
「Smalltalk の例」 「
'Hello mate'の includeSubstring: 'e' は true を返します」 「
' word ' の includeSubstring: '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を返します
探す
例
- コモンリスプ
( search "e" "Hello mate" ) ; 1 を返します( search "z" "word" ) ; NIL を返します
- C#
"Hello mate" . IndexOf ( "e" ); // 1 を返します"Hello mate" . IndexOf ( "e" , 4 ); // 9 を返します"word" . IndexOf ( "z" ); // -1 を返します
- 楽
"Hello, there!" . index ( 'e' ) # 1 を返します "Hello, there!" . 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 を返します
- 雑談
「Hello mate」 indexOfSubCollection: 「ate」は 「8 を返します」
「Hello mate」 indexOfSubCollection: 「late」 は「0 を返します」
I ' Hello mate ' indexOfSubCollection: 'late' ifAbsent: [ 99 ] "99 を返します"
'Hello mate' indexOfSubCollection: 'late' ifAbsent: [自己 エラー] "例外が発生します"
キャラクターを探す
// C# の例
"Hello mate" . IndexOf ( 'e' ); // 1 を返します"word" . IndexOf ( 'z' ) // -1 を返します
; Common Lisp の例
( position #\e "Hello mate" ) ; 1 を返します( position #\z "word" ) ; NIL を返します
^a 文字セットが与えられると、SCANは最初に見つかった文字の位置を返します。 [19]一方、VERIFYはセットに属さない最初の文字の位置を返します。 [20]
形式
// C# の例
String . Format ( "My {0} costs {1:C2}" , "pen" , 19.99 ); // "My pen costs $19.99" を返します
// Object Pascal (Delphi)形式の例( 'My %s costs $%2f' , [ 'pen' , 1 9.99 ]) ; // "My pen costs $19.99" を返します
// Java
文字列の例。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 のコストは $ %.2f です" % ( "pen" , 19.99 ); # "My pen costs $19.99" を返します
"My {0} のコストは $ {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 を返します
索引
#検索 を参照
インデックス
#検索 を参照
命令
#検索 を参照
強制的に
#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" を返します
レン
#長さ を参照
長さ
// C# の例
"hello" . Length ; // 5 を返す"" . Length ; // 0 を返す
# Erlangの例string : len ( "hello" ). % は 5 を返しますstring : len ( "" ). % は 0 を返します
# Perl の例 5
length ( "hello" ); # 5 を返すlength ( "" ); # 0 を返す
# Raku の例
"🏳️🌈" . chars ; chars "🏳️🌈" ; # 両方とも 1 を返します
"🏳️🌈" . codes ; codes "🏳️🌈" ; # 両方とも 4 を返します
"" . 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 を返します
見つける
#検索 を参照
小文字
// C# の例
"Wiki は高速を意味しますか?" . ToLower (); // "wiki は高速を意味しますか?"
; Scheme の例
( use-modules ( srfi srfi-13 )) ( string-downcase "Wiki means fast?" ) ; "wiki means fast?"
/* C の例 */
#include <ctype.h> #include <stdio.h> int main ( void ) { char string [] = "Wiki means fast?" ; int i ; for ( i = 0 ; i < sizeof ( string ) - 1 ; ++ i ) { /* 文字を 1 つずつその場で変換します */ string [ i ] = tolower ( string [ i ]); } puts ( string ); /* "wiki means fast?" */ 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 の例
を逆にすると"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 を返します
右
// Examples in Java; extract rightmost 4 characters
String str = "CarDoor";
str.substring(str.length()-4); // returns 'Door'
# Examples in Raku
"abcde".substr(*-3); # returns "cde"
"abcde".substr(*-8); # 'out of range' error
/* Examples in Rexx */
right("abcde", 3) /* returns "cde" */
right("abcde", 8) /* returns " abcde" */
right("abcde", 8, "*") /* returns "***abcde" */
; Examples in Scheme
(use-modules (srfi srfi-13))
(string-take-right "abcde", 3) ; returns "cde"
(string-take-right "abcde", 8) ; error
' Examples in Visual Basic
Right("sandroguidi", 3) ' returns "idi"
Right("sandroguidi", 100) ' returns "sandroguidi"
rpartition
# 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文字列の例:トークン( "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)
スプリント
#フォーマット を参照
ストリップ
#trim を参照
strcmp
#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 の例 文字
列: substr ( "abc" , 2 , 1 ). % "b" を返します文字列: 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 = 'これは例です。'
UPPER A /* "これは例です。" */
/* 例 #3 */
A = 'upper using Translate Function.'
Translate UPPER VAR A Z /* Z="UPPER USING TRANSLATE FUNCTION." */
; Scheme の例
( use-modules ( srfi srfi-13 )) ( string-upcase "Wiki means fast?" ) ; "WIKI MEANS FAST?"
' Visual Basic
UCaseの例( "Wiki は高速を意味しますか?" ) ' "WIKI は高速を意味しますか?"
トリム
trimor は、strip文字列の先頭、末尾、または先頭と末尾の両方から空白を削除するために使用されます。
その他の言語
組み込みのトリム関数がない言語では、通常、同じタスクを実行するカスタム関数を作成するのは簡単です。
オーストラリア
APL では正規表現を直接使用できます。
トリム← '^ +| +$' ⎕R ''
あるいは、先頭と末尾のスペースを除去するブールマスクを組み合わせた機能的なアプローチもあります。
トリム← { ⍵ /⍨ ( ∨ \ ∧ ∘ ⌽∨ \∘ ⌽ ) ' ' ≠ ⍵ }
または、先頭のスペースを 2 回逆にして削除します。
トリム← { ( ∨ \ ' ' ≠ ⍵ ) / ⍵ } ∘ ⌽ ⍣ 2
AWK
AWKでは、正規表現を使用してトリミングできます。
ltrim ( v ) = gsub ( /^[ \t]+/ , "" , v )
rtrim ( v ) = gsub ( /[ \t]+$/ , "" , v )
トリム( v ) = ltrim ( v ); rtrim ( v )
または:
関数 ltrim ( s ) { sub ( /^[ \t]+/ , "" , s ); return s }
関数 rtrim ( s ) { sub ( /[ \t]+$/ , "" , s ); return s }
関数 trim ( s ) { return rtrim ( ltrim ( s ) ); }
C++ の
There is no standard trim function in C or C++. Most of the available string libraries[55] for C contain code which implements trimming, or functions that significantly ease an efficient implementation. The function has also often been called EatWhitespace in some non-standard C libraries.
In C, programmers often combine a ltrim and rtrim to implement trim:
#include <string.h>
#include <ctype.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] != '\0' && isspace((unsigned char) str[n])) {
n++;
}
memmove(str, str + n, strlen(str) - n + 1);
}
void trim(char *str)
{
rtrim(str);
ltrim(str);
}
The open source C++ library Boost has several trim variants, including a standard one:[56]
#include <boost/algorithm/string/trim.hpp>
trimmed = boost::algorithm::trim_copy("string");
With boost's function named simply trim the input sequence is modified in-place, and returns no result.
Another open source C++ library Qt, has several trim variants, including a standard one:[57]
#include <QString>
trimmed = s.trimmed();
The Linux kernel also includes a strip function, strstrip(), since 2.6.18-rc1, which trims the string "in place". Since 2.6.33-rc1, the kernel uses strim() instead of strstrip() to avoid false warnings.[58]
Haskell
A trim algorithm in Haskell:
import Data.Char (isSpace)
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
may be interpreted as follows: f drops the preceding whitespace, and reverses the string. f is then again applied to its own output. Note that the type signature (the second line) is optional.
J
The trim algorithm in J is a functional description:
trim =. #~ [: (+./\ *. +./\.) ' '&~:
That is: filter (#~) for non-space characters (' '&~:) between leading (+./\) and (*.) trailing (+./\.) spaces.
JavaScript
There is a built-in trim function in JavaScript 1.8.1 (Firefox 3.5 and later), and the ECMAScript 5 standard. In earlier versions it can be added to the String object's prototype as follows:
String.prototype.trim = function() {
return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
};
Perl
Perl 5 has no built-in trim function. However, the functionality is commonly achieved using regular expressions.
Example:
$string =~ s/^\s+//; # remove leading whitespace
$string =~ s/\s+$//; # remove trailing whitespace
or:
$string =~ s/^\s+|\s+$//g ; # remove both leading and trailing whitespace
These examples modify the value of the original variable $string.
Also available for Perl is StripLTSpace in String::Strip from CPAN.
There are, however, two functions that are commonly used to strip whitespace from the end of strings, chomp and chop:
chopremoves the last character from a string and returns it.chompremoves the trailing newline character(s) from a string if present. (What constitutes a newline is $INPUT_RECORD_SEPARATOR dependent).
In Raku, the upcoming sister language of Perl, strings have a trim method.
Example:
$string = $string.trim; # remove leading and trailing whitespace
$string .= trim; # same thing
Tcl
The Tcl string 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:
set string onomatopoeia
set trimmed [string trim $string aeiou] ;# result is nomatop
set r_trimmed [string trimright $string aeiou] ;# result is onomatop
set l_trimmed [string trimleft $string aeiou] ;# result is nomatopoeia
XSLT
XSLT includes the function normalize-space(string) which strips leading and trailing whitespace, in addition to replacing any whitespace sequence (including line breaks) with a single space.
Example:
<xsl:variable name='trimmed'>
<xsl:value-of select='normalize-space(string)'/>
</xsl:variable>
XSLT 2.0 includes regular expressions, providing another mechanism to perform string trimming.
Another XSLT technique for trimming is to utilize the XPath 2.0 substring() function.
References
- ^ a b c d e the index can be negative, which then indicates the number of places before the end of the string.
- ^ In Rust, the str::chars method iterates over code points and the std::iter::Iterator::nth method on iterators returns the zero-indexed nth value from the iterator, or
None. - ^ the index can not be negative, use *-N where N indicate the number of places before the end of the string.
- ^ In C++, the overloaded operator<=> method on a string returns a std::strong_ordering object (otherwise
std::weak_ordering):less,equal(same asequivalent), orgreater. - ^ returns LESS, EQUAL, or GREATER
- ^ returns LT, EQ, or GT
- ^ returns
.TRUE.or.FALSE.. These functions are based on the ASCII collating sequence. - ^ a b IBM extension.
- ^ In Rust, the Ord::cmp method on a string returns an Ordering:
Less,Equal, orGreater. - ^ a b c d e f In Rust, the operators
==and!=and the methodseq,neare implemented by the PartialEq trait, and the operators<,>,<=,>=and the methodslt,gt,le,geare implemented by the PartialOrd trait. - ^ The operators use the compiler's default collating sequence.
- ^ modifies
string1, which must have enough space to store the result - ^ In Rust, the
+operator is implemented by the Add trait. - ^ See the str::contains method.
- ^ See the std::basic_string::contains method.
- ^ a b startpos is IBM extension.
- ^ a b See the str::find method.
- ^
startposis IBM extension. - ^ "scan in Fortran Wiki". Fortranwiki.org. 2009-04-30. Retrieved 2013-08-18.
- ^ "verify in Fortran Wiki". Fortranwiki.org. 2012-05-03. Retrieved 2013-08-18.
- ^
formatstringmust be a fixed literal at compile time for it to have the correct type. - ^ See std::format, which is imported by the Rust prelude so that it can be used under the name
format. - ^ See the slice::join method.
- ^ if n is larger than the length of the string, then in Debug mode ArrayRangeException is thrown, in Release mode, the behaviour is unspecified.
- ^ if n is larger than the length of the string, Java will throw an IndexOutOfBoundsException
- ^ a b if n is larger than length of string, raises Invalid_argument
- ^ a b if n is larger than length of string, throw the message "StringTake::take:"
- ^ a b c In Rust, strings are indexed in terms of byte offsets and there is a runtime panic if the index is out of bounds or if it would result in invalid UTF-8. A
&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 withstrbeing the type being indexed. The str::get method is the non-panicking way to index. It returnsNonein the cases in which indexing would panic. - ^ Ruby lacks Unicode support
- ^ See the str::len method.
- ^ 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.
- ^ operates on one character
- ^ a b The
transformfunction exists in thestd::namespace. You must include the<algorithm>header file to use it. Thetolowerandtoupperfunctions are in the global namespace, obtained by the<ctype.h>header file. Thestd::tolowerandstd::touppernames are overloaded and cannot be passed tostd::transformwithout a cast to resolve a function overloading ambiguity, e.g.std::transform(string.begin(), string.end(), result.begin(), (int (*)(int))std::tolower); - ^
std::stringonly, result is stored in stringresultwhich is at least as long asstring, and may or may not bestringitself - ^ a b only ASCII characters as Ruby lacks Unicode support
- ^ See the str::to_lowercase method.
- ^ See the str::replace method.
- ^ a b c d e The "find" string in this construct is interpreted as a regular expression. Certain characters have special meaning in regular expressions. If you want to find a string literally, you need to quote the special characters.
- ^ third parameter is non-standard
- ^ 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.
- ^ See the str::rfind method.
- ^ "Annotated ES5". Es5.github.com. Archived from the original on 2013-01-28. Retrieved 2013-08-18.
- ^ if n is larger than length of string, then in Debug mode ArrayRangeException is thrown, and unspecified behaviour in Release mode
- ^ See the str::split and str::rsplit methods.
- ^ a b c d e f g
startposcan be negative, which indicates to start that number of places before the end of the string. - ^ a b
numCharscan be negative, which indicates to end that number of places before the end of the string. - ^
startposcan not be negative, use * - startpos to indicate to start that number of places before the end of the string. - ^
numCharscan not be negative, use * - numChars to indicate to end that number of places before the end of the string. - ^ a b c d e
endposcan be negative, which indicates to end that number of places before the end of the string. - ^
std::stringonly, result is stored in string result which is at least as long as string, and may or may not be string itself - ^ 「uppercase - Kotlinプログラミング言語」Kotlin 。 2024年11月9日閲覧。
- ^ Rust では、str::to_uppercase メソッドは、Unicode の規則に従って小文字を大文字に変更した、新しく割り当てられた文字列を返します。
- ^ Rust では、str::trim メソッドは元の への参照を返します
&str。 - ^ “トリム – GNU Pascal priručnik”. Gnu-pascal.de 。2013 年 8 月 24 日に取得。
- ^ 「文字列ライブラリの比較」。And.org 。 2013年8月24日閲覧。
- ^ 「Usage – 1.54.0」。Boost.org。2013年5月22日。 2013年8月24日閲覧。
- ^ [1] 2009年8月2日アーカイブ、Wayback Machine
- ^ dankamongmen. 「sprezzos-kernel-packaging/changelog at master · dankamongmen/sprezzos-kernel-packaging · GitHub」。Github.com 。 2016年5月29日閲覧。
