Ruby文字列の空白記号の追加または削除処理
3167 ワード
Rubyは、スペースを削除する方法を定義します.
str.gsub(pattern,replacement):一部の文字列を置換
str.strip:前後のスペースを削除した文字列を返します.
str.chomp:文字列の末尾のrまたはrを削除
str.chop:文字列の最後の文字を削除し、終了文字がrの場合は両方を削除し、文字列が空の場合は空を返します.
str.ljust(integer,padstr='):integerがstrの長さより大きい場合、strが左padstrに埋め込まれた文字列がintegerの長さで返されます.
str.rjust(integer,padstr='):integerがstrの長さより大きい場合、integerの長さを返します.strは右側のpadstrに埋め込まれた文字列です.
str.center(width,padstr='):widthがstrの長さの約1つである場合、strが真ん中の両側にpadstrで埋め込まれた文字列が返されます.
str.gsub(pattern,replacement):一部の文字列を置換
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>"
"hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101 108 108 111 "
"hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}') #=> "h{e}ll{o}"
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"
' he l l o '.gsub(' ','') #=> "hello"
str.strip:前後のスペースを削除した文字列を返します.
" hello ".strip #=> "hello"
"\tgoodbye\r
".strip #=> "goodbye"
" hello ".lstrip #=> "hello "
"hello".lstrip #=> "hello"
" hello ".rstrip #=> " hello"
"hello".rstrip #=> "hello"
str.chomp:文字列の末尾のrまたはrを削除
"hello".chomp #=> "hello"
"hello
".chomp #=> "hello"
"hello\r
".chomp #=> "hello"
"hello
\r".chomp #=> "hello
"
"hello\r".chomp #=> "hello"
"hello
there".chomp #=> "hello
there"
"hello".chomp("llo") #=> "he"
str.chop:文字列の最後の文字を削除し、終了文字がrの場合は両方を削除し、文字列が空の場合は空を返します.
"string\r
".chop #=> "string"
"string
\r".chop #=> "string
"
"string
".chop #=> "string"
"string".chop #=> "strin"
"x".chop.chop #=> ""
str.ljust(integer,padstr='):integerがstrの長さより大きい場合、strが左padstrに埋め込まれた文字列がintegerの長さで返されます.
"hello".ljust(4) #=> "hello"
"hello".ljust(20) #=> "hello "
"hello".ljust(20, '1234') #=> "hello123412341234123"
str.rjust(integer,padstr='):integerがstrの長さより大きい場合、integerの長さを返します.strは右側のpadstrに埋め込まれた文字列です.
"hello".rjust(4) #=> "hello"
"hello".rjust(20) #=> " hello"
"hello".rjust(20, '1234') #=> "123412341234123hello"
str.center(width,padstr='):widthがstrの長さの約1つである場合、strが真ん中の両側にpadstrで埋め込まれた文字列が返されます.
"hello".center(4) #=> "hello"
"hello".center(20) #=> " hello "
"hello".center(20, '123') #=> "1231231hello12312312"