1. 程式人生 > >Ruby String常用函式

Ruby String常用函式

單引號的字串中,連續兩個\會被一個\替換

例:

‘nds\\’  #->  nds\

‘nds\\\’  #-> 出錯

‘nds\\\y’  #->  nds\\y

‘nds\\\\’ # ->  nds\\

例:

‘nds\’’  #-> nds’

‘nds\’\\’ #-> 出錯

3、  +將字串連線起來

例:

'abc' + 'def'       #=> 'abcdef'

str * times

例:

"abc" * 4       #=> "abcabcabcabc"

可支援全部的轉義字元及用#{exp}將Ruby中的值插入字串中

例:

i = 5

str = “ abab#{i}cjd”  #->abab5cjd

“#{ho *3} happy new year”  #->ho ho ho happy new year

str.length => integer

str.size=> integer

例如:

“string”.length       #->5          # 字串的長度

“string”.size         #->5                # 字串的長度

str.include? other_str => true or false

例如:“string”.include?”in”  #->true         # 檢查string中是否包含in

str.insert(index, other_str)=> str

例如:

        “string”.insert(0,‘a’)    #-> astring             # 在指標為0的位置插入a,指標從0起

“string”.insert(-1,‘a’)    #-> stringa           # 逆向指標為-1的位置插入a,指標從-1起

str.split(pattern=$;, [limit]) =>anArray 

例如:

“string  abc”.split    #->[“string” ,”abc”]   # 將字串進行分割,預設的分隔符為空格

“string abc”.split(“ab”)    #->[“string  ” ,” c”] # 將字串以ab為分隔符進行進行分割

"1,2,,3,4,,".split(',',4)     # -> ["1","2", "", "3,4,,"] # split的第二個引數用於限制分割後的部分數

str.replace(other_str)=> str                # replace來替換整個str,str本身也被改變。

sub生成並返回替換後的字串。而sub!會修改str本身並返回結果。若沒有進行替換時返回nil。sub只替換第一次匹配的部分,gsub替換所有匹配的部分。

例如:

str = “hello”               

str.sub(/[aeiou]/, '*')       #->"h*llo"      # str = “hello”

str.sub!(/[aeiou]/, '*')        #->"h*llo"      # str = "h*llo"

str.gsub(/[aeiou]/, '*')        #-> "h*ll*"      #將母音替換成*號

str.gsub(/./){|s| s[0]+’ ‘}        #-> "h e l l l o"    #將所有元素後加空格

str.replace(“he”)             #->”he”       #str=” he”

str.delete([other_str]+) => new_str   #刪除引數交集出現的所有字元,返回一個新字串

str. delete! ([other_str]+) => str   #原字串會被改變

例:

"hello".delete "l","lo"          #-> "heo"  #刪掉所有的l

"hello".delete "lo"             #-> "he" #刪掉所有的l及o

str. strip => new_str               #刪除頭部和尾部的空白

str.strip! =>str                                 #刪除頭部和尾部的空白,原字串本身被改變,若無刪除動作,則返回nil,str本身不變

str.lstrip => new_str               #刪除頭部的空白

str. lstrip !=> str                                      #刪除頭部的空白,原字串本身被改變,若頭部無空白,則返回nil,str本身不變

str.rstrip => new_str              #刪除尾部的空白

str.rstrip !=> str                                     #刪除尾部的空白,原字串本身被改變,若尾部無空白,則返回nil,str本身不變

例:

p " abc\n".lstrip     #=>"abc\n"

p "\t abc\n".lstrip   #=> "abc\n"

p "abc\n".lstrip      #=> "abc\n"

str = "\nabc"

p str.lstrip           #=>"abc"

p str                  #=>"\nabc"  (無變化)

str = "  abc"

p str.lstrip!          #=>"abc"

p str                  #=>"abc"  (有變化)

str = "abc"

p str.lstrip!          #=>nil

p str                  #=>"abc"

str.match(pattern)=> matchdata or nil

例:

 puts “hello”.match(/ll./)   #=> <MatchData “llo”>

str.reverse => new_str

str.reverse !=> str       #str本身會改變

    例:

"hello".reverse     #=> "olleh"

str.squeeze([other_str]*) => new_str

str.squeeze!([other_str]*) => str            #str本身被改變,若無刪除動作,返回nil,

                                                                                           str不變

例:

"hello moon".squeeze     #=> "helo mon"   #預設去掉串中所有重複的字元

" hello moon  ".squeeze(" ")  #=> " hello moon "   #去掉串中重複的空格

" hello moon”. squeeze ("m-z")     #=> " hello mon " #去掉指定範圍內的重複字元

to_f:將字串看作是10進位制數形式,並將其變為浮點數Float。將不能被看作浮點數的那個部分之前的內容變為浮點數。若變換物件是空字串則返回 0.0 。

         例:

p "10".to_f    #=> 10.0

p "10e2".to_f  #=> 1000.0

p "e2".to_f  # =>0.0      #頭部第一個字元不可被看作浮點數

p "1e-2".to_f  #=> 0.01

p ".1".to_f    #=> 0.1

p " \n10".to_f # => 10.0       # 頭部的空白被忽略

p "1_0_0".to_f # => 100.0        # `_' 被忽略

p "".to_f      #=> 0.0

to_i:將字串看作是10進位制數形式,並將其變為整數。若遇到不能變為整數的字元,就將它前面的內容變為整數。若變換物件為空字串,則返回0。

例:

p " 10".to_i    #=> 10

p " 10e2".to_i    #=> 10

p "1e-2".to_f  #=> 1

p "010".to_i    #=> 10

p "-010".to_i   #=> -10

p "0x11".to_i   #=> 0

p ".1".to_i  # =>0

to_i(base) :通過指定不同的基數,還可以進行2~36進位制的轉換。若指定為0時,則通過 prefix 來判斷基數(相反地,只有將其指定為0時,才會識別prefix)。若使用了0、2~36之外的引數時,會引發ArgumentError異常。

         例:

p "0b10".to_i(0)  #=> 2

p "0b10".to_i(2)  #=> 2

p "0o10".to_i(0)  # => 8

p "010".to_i(0)   #=> 8

p "0d10".to_i(0)  #=> 10

p "0d10".to_i(8)  #=> 0

p "0x10".to_i(0)  #=> 16

str.chop :刪除字串str的最後一個字元,並返回新字串

#若字串以\r\n結尾,則兩個字元都刪去

#若字串為空串,則返回空串

str.chop !:修改str本身並返回結果,若沒做修改,則返回nil。

         例:

"string\r\n".chop           #->"string"

"string\n\r".chop           #->"string\n"

"string".chop                          #->"strin"

"s".chop.chop                #->""

str.chomp(endstr) :刪除str的字尾endstr,如果未指定endstr,則刪除回車換行符(\r、\n和\r\n);若endstr的取值是nil的話,將不作任何的動作。

str.chomp!(endstr) :修改str本身並返回結果,若沒做修改,則返回nil。

例:

"hello\r\n".chomp                        #->"hello"

"hello".chomp("lo")                     #->"hel"

"hello".chomp("l")                        #->nil

arg為陣列時,使用sprintf(self,*args)

arg為非陣列時,使用sprintf(self,args)

         例:

name = "Bob"

age = 28

str = sprintf("Hi, %s... I see you're %d years old.", name, age)    #->”Hi, Bob... I see you're 28 

                                                                                                                                    years old”

格式 字串

例:

p "%#x"     % 10       # => "0xa"

p "%#x,%#o" % [10, 10]  # => "0xa,012"

str.center(width)

str.ljust(width)

str.rjust(width)

str.center(width[,padding])

str.ljust(width[,padding])

str.rjust(width[,padding])

分別返回居中、靠左、靠右的字串,當字串長度超過width時,將返回原字串的拷貝;若使用了第二引數padding的話,將使用padding來填充空白。

例:

str = "Moby-Dick"

s1 = str.ljust(13)            #"Moby-Dick    "

s2 = str.center(13)                #"  Moby-Dick  "

s3 = str.rjust(13)                   #"    Moby-Dick"

s4 = str.rjust(13)                   #"****Moby-Dick"

str.center(1).id== str.id   # => false      #返回原字串的拷貝

str.capitalize:將首字元(若為字母的話)改為大寫字母,其餘的改為小寫字母,生成並返回

修改後的字串。。

str.capitalize!:會修改str本身並返回結果,若未作修改時返回nil。

例:

"foobar".capitalize              # => "Foobar"

str.downcase:將字串中的大寫字母都改為小寫字母,生成並返回修改後的字串

str.downcase!:會修改str本身並返回結果,若沒有作修改,則返回nil.

str.upcase:將字串中的小寫字母都改為大寫字母,生成並返回修改後的字串

str.upcase!:會修改str本身並返回結果,若沒有作修改,則返回nil.

str. swapcase:將所有的大寫字母改為小寫字母,小寫字母改為大寫字母,生成並返回

修改後的字串

str. swapcase!:會修改str本身並返回結果,若沒有作修改,則返回nil.

例:

s = "Hello,World"

s.downcase                      #"hello,world"

s.upcase                         #"HELLO,WORLD"

s.swapcase                        #"hELLO,wORLD"

“=~”:與正則表示式的匹配           

例:

if string =~ /[a-z]/     #檢查字串中是否有小寫字元

  puts "string contains lowercase charcters"

end

if string =~ /[A-Z]/               #檢查字串中是否有大寫字元

  puts "string contains uppercase charcters"

end

if string =~ /[A-Z]/ and string =~ /a-z/  #檢查字串中是否既有大寫又有小寫字元

  puts "string contains mixed case"

end

if string[0..0] =~ /[A-Z]/         #檢查字串中第一個字元是否大寫

  puts "string starts with a capital letter"

end

p “AhdhBBN”=~/[A-Z]/   返回0

[v1] 

字串與正則相關的方法還有matchscan,match返回第一個匹配物件,scan返回所有符合正則表示式的陣列

例:

“hello”.match(/[a-h]/)             #<MatchData “h”>

“hello”.scan(/[a-h]/)                               #[“h”,”e”]

str[num1,num2]:num1代表取字串的偏移位置,num2表示取的長度,其中num1可以是負數:

例:

str = "Humpty Dumpty"

sub1 = str[7,4]         # "Dump"

sub2 = str[7,99]        # "Dumpty" (超過的長度按實際長度來取)

sub3 = str[10,-4]       # nil (長度為負數了)

   str1 = "Alice"

     sub1 = str1[-3,3]   # "ice"

    str2 = "Through the Looking-Glass"

    sub3 = str2[-13,4]  # "Look"

Range取子串:利用腳標取子串

例:

        str = "Winston Churchill"

        sub1 = str[8..13]    # "Church"

        sub2 = str[-4..-1]   # "hill"

        sub3 = str[-1..-4]   # “”

     sub4 = str[25..30]   # nil

     str = "Alistair Cooke"

    sub1 = str[/l..t/]   # "list"

    sub2 = str[/s.*r/]   # "stair"

    sub3 = str[/foo/]    # nil

如果給出的是一個字串,則如果目標字串中含有這個給出的字串,則返回這個給出的字串,否則返回nil:

         str = "theater"

         sub1 = str["heat"]  # "heat"

         sub2 = str["eat"]   # "eat"

           sub3 = str["ate"]   # "ate"

         sub4 = str["beat"]  # nil

          sub5 = str["cheat"] # nil

如果給出的是一個數字,則返回的是該數字對應索引處字元的ASCII碼:

   str = "Aaron Burr"

   ch1 = str[0]     #A

   ch1 = str[1]     #a

ch3 = str[99]    # nil

 [v1]返回匹配正則表示式中的第一個字元的位數,p “ssD”=~/[A-Z]/ 返回2