Ruby字符串處理函數

Ruby字符串處理函數

1.返回字符串的長度

str.length => integer  

2.判斷字符串中是否包含另一個串

str.include? other_str   #true or false   
"hello".include? "lo"    #=> true   
"hello".include? "ol"    #=> false   
"hello".include? ?h      #=> true  

3.字符串插入:

str.insert(index, other_str)      #str  
"abcd".insert(0, 'X') #=> "Xabcd"  
"abcd".insert(3, 'X') #=> "abcXd"  
"abcd".insert(4, 'X')  #=> "abcdX"  
"abcd".insert(-3, 'X') #=> "abXcd"  
"abcd".insert(-1, 'X') #=> "abcdX" 

4.字符串分隔,默認分隔符爲空格

str.split(pattern=$;, [limit]) #  anArray  
" now's the time".split  #=> ["now's", "the", "time"]  
"1, 2.34,56, 7".split(%r{,\s*})  #=> ["1", "2.34", "56", "7"]  
"hello".split(//)  #=> ["h", "e", "l", "l", "o"]  
"hello".split(//, 3)  #=> ["h", "e", "llo"]  
"hi mom".split(%r{\s*})  #=> ["h", "i", "m", "o", "m"]   
"mellow yellow".split("ello")  #=> ["m", "w y", "w"]  
"1,2,,3,4,,".split(',')  #=> ["1", "2", "", "3", "4"]  
"1,2,,3,4,,".split(',', 4)  #=> ["1", "2", "", "3,4,,"] 

也可以指定切分符:

"apples, pears, and peaches".split(", ")      # ["apples", "pears", "and peaches"]
"lions and tigers and bears".split(/ and /)   # ["lions", "tigers", "bears"]

splite方法的第二個參數用來限制切分的返回結果個數,具體效果規則如下:
1.如果省略這個參數,則切分結果中末尾爲null的結果將被壓縮掉
2.如果是正數,則結果按照指定的限制數量進行切分,尾部的null結果也將會保留做爲結果
3.如果是負數,則切分結果數量無限制,並且保留尾部的null結果。
例如:

str = "alpha,beta,gamma,,"
list1 = str.split(",")     # ["alpha","beta","gamma"]
list2 = str.split(",",2)   # ["alpha", "beta,gamma,,"]
list3 = str.split(",",4)   # ["alpha", "beta", "gamma", ","]
list4 = str.split(",",8)   # ["alpha", "beta", "gamma", "", ""]
list5 = str.split(",",-1)  # ["alpha", "beta", "gamma", "", ""]

5、格式化字符串

Ruby的字符串格式話沿用了C的格式,在C中可用於sprintf或printf的格式話字符在Ruby中同樣適用:

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

String類有個%方法,可以方面的做格式化的工作,它接受任何類型的單個值或一個數組:

str = "%-20s  %3d" % [name,age]

上面這個和下面這個式子是等效的

str = sprintf("%-20s  %3d", name, age)

我們還可以使用ljust,rjust,center方法來格式化我們的字符串:

str = "Moby-Dick"
s1 = str.ljust(13)    #"Moby-Dick    "
s2 = str.center(13)     #"  Moby-Dick  "
s3 = str.rjust(13)    #"    Moby-Dick"

6、控制字符串的大小寫

Ruby的String類提供了一組豐富的方法來控制大小寫:

s = "Hello,World"
s1 = s.downcase    #"hello,world"
s2 = s.upcase     #"HELLO,WORLD"

capitalize方法把字符串第一個字符變大寫,其餘都是小寫:

s3 = s.capitalize    #"Hello,world"

swapcase則是把字符串中的每個字符的大小寫轉換一下(原來大寫的都小寫,反之亦然):

s = "HELLO,world"
s1 = s.swapcase     #"hello,WORLD"

這些方法都有相應的in-place方法

 (upcase!,downcase!,capitalize!,swapcase!)

雖然,Ruby沒有提供內置的判斷字符是否是大小寫的方法,但是,這不是問題,我們可以通過正則表達式來完成這一點:

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

字符串的子串

Ruby提供了多種訪問操作字符串子串的方式,我們可以來看一下:

1.如果給出一組數字,則第一個數字代表取字符串的偏移位置,第二個數字表示

取的長度:

str = "Humpty Dumpty"
sub1 = str[7,4]         # "Dump"
sub2 = str[7,99]        # "Dumpty" (超過的長度按實際長度來取)
sub3 = str[10,-4]       # nil (長度爲負數了)

記住,上面的形式,很多從別的語言轉過來的ruby初學者會認爲給出的兩個數字是子串的開始和結束位置的偏移,這是錯誤的,務必記住。
給出的偏移是負數也是可以的,這樣,位置將從字符串末尾開始計算:

    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]   # nil
    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]     # 65
    ch1 = str[1]     # 97
    ch3 = str[99]    # nil

同樣,我們不僅可以通過上面的方式訪問子串,還可以來向字符串設置內容:

str1 = "Humpty Dumpty"
str1[7,4] = "Moriar"     # "Humpty Moriarty"
str2 = "Alice"
str2[-3,3] = "exandra"   # "Alexandra"
str3 = "Through the Looking-Glass"
str3[-13,13]  = "Mirror" # "Through the Mirror"
str4 = "Winston Churchill"
str4[8..13] = "H"        # "Winston Hill"
str5 = "Alistair Cooke"
str5[/e$/] ="ie Monster" # "Alistair Cookie Monster"
str6 = "theater"
str6["er"] = "re"        # "theatre"
str7 = "Aaron Burr"
str7[0] = 66             # "Baron Burr"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章