在Ruby中建立一個字符串有多種方式。能夠有兩種方式表示一個字符串:用一對單引號包圍字符('str')或用一對雙引號包圍字符("str") 這兩種形式的區別在於對於包圍的字符串的處理,用雙引號構造的字符串能處理更多的轉移字符。 正則表達式
除了這兩種方式,ruby還支持3種方式去構建字符串:%q、%Q和here documents。 api
%q後面用一對分界符包圍的字符能夠構造單引號字符串。 數組
%Q後面用一對分界符包圍的字符能夠構造雙引號字符串。 ruby
PS:分界符能夠是任何一個非字母數字的單字節字符,如() [] {} <> //。app
here documents 函數
str=<<END_OF_STRINGthis
a stringspa
END_OF_STRING3d
ruby中並不會去掉字符串開頭的空格。 索引
#5種構建字符串hello world的方法對比
'hello world'
"hello world"
%q/hello world/
%Q{hello world}
str=<<EOS
hello world
EOS
單引號和雙引號在某些狀況下有不一樣的做用.一個由雙引號括起來的字符串容許字符由一個前置的斜槓引出,並且能夠用#{}內嵌表達式.而 單引號括起來的字符串並不會對字符串做任何解釋
Ruby的字符串操做比C更靈巧,更直觀.好比說,你能夠用+把幾個串連起來,用*把一個串重複好幾遍:
"foo" + "bar" #"foobar"
"foo" * 2 # #"foofoo"
抽取字符(注意:在Ruby裏,字符被視爲整數):
負的索引指從字符串尾算起的偏移量,
word[0]
word[-1]
herb[0,1]
herb[-2,2]
herb[0..3]
herb[-5..-2]
檢查相等:
"foo" == "foo"
split()
trim()
indexOf()
replaceAll()
String.split
"hello world".split( " ")
returns [ "hello", "world" ].
String.strip
" hello world ".strip
returns "hello world".
String.index
"hello world".index( "w")
returns 6.
String.gsub(/\s/, ',')
"hello word".gsub(\/s\, ',')
returns "hello,word"
p.s.
sub() replace first
gsub() replace all
str1 = 'Hello world'
str2 = "Hello world" #雙引號比單引號定義的字符串更增強大,如可提供轉移字符等
str3 = %q/Hello world/ # %q將後面的字符串轉換成單引號字符串,後面的/爲自定義的特殊符號,在字符串結尾處也需有該特殊符號
str4 = %Q/Hello world/ # %Q將定義雙引號字符串
str = <<The_Text Hello World! Hello Ruby. The_Text
puts str #這種方式比較有意思,str的內容爲<<The_Text到下個The_Text之間的內容,The_Text爲自定義的文本
arr = [1,1,1,2,2]
puts arr.join(",") #數組用join轉換成字符串
str = 'this' + " is"
str += ' you'
str <<" string"<<"."
puts str * 2 #this is you string.this is you string.
puts str[-12,12] # you string. 意味從後截取多少個字符
\n \t \'
字符串轉移只對雙引號字符串生效,例外爲單引號,如:
str = 'this\'s you string.'
字符串內嵌入表達式用 #{ }
def Hello(name)
"Hello #{neme}!"
end
str.delete(str1,str2,...)
#刪除參數交集出現的全部字符,返回一個新字符串,如:
"hello world".delete("l") #返回"heo word"
"hello world".delete("lo","o") #返回"hell wrld"str.delete!(str1,str2,...)
#直接對str進行刪除操做,同時返回str如:
str="hello world"
str2=str.delete("l") #str爲"hello world",str2爲"heo word"
str.delete!("l") #str爲"heo word"
str.gsub(pattern, replacement) => new_str
str.gsub(pattern) {|match| block } => new_str
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*" #將元音替換成*號
"hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>" #將元音加上尖括號,\1表示保留原有字符???
"hello".gsub(/./) {|s| s[0].to_s + ' '}#=> "104 101 108 108 111 "
字符串替換二:
str.replace(other_str) => str
s = "hello" #=> "hello"
s.replace "world" #=> "world"
str.delete([other_str]+) => new_str
"hello".delete "l","lo" #=> "heo"
"hello".delete "lo" #=> "he"
"hello".delete "aeiou", "^e" #=> "hell"
"hello".delete "ej-m" #=> "ho"
str.lstrip => new_str
" hello ".lstrip #=> "hello "
"hello".lstrip #=> "hello"
str.match(pattern) => matchdata or nil
str.reverse => new_str
"stressed".reverse #=> "desserts"
str.squeeze([other_str]*) => new_str
"yellow moon".squeeze #=> "yelow mon" #默認去掉串中全部重複的字符
" now is the".squeeze(" ") #=> " now is the" #去掉串中重複的空格
"putters shoot balls".squeeze("m-z") #=> "puters shot balls" #去掉指定範圍內的重複字符
str.to_i=> str
"12345".to_i #=> 12345
"hello".chomp #=> "hello"
"hello\n".chomp #=> "hello"
"hello\r\n".chomp #=> "hello"
"hello\n\r".chomp #=> "hello\n"
"hello\r".chomp #=> "hello"
"hello".chomp("llo") #=> "he"
"string\r\n".chop #=> "string"
"string\n\r".chop #=> "string\n"
"string\n".chop #=> "string"
"string".chop #=> "strin"
#求字符串長度,返回int
str.size
str.length
str.chop
#刪除字符串str的最後一個字符,並返回新字符串
#若字符串以\r\n結尾,則兩個字符都刪去
#若字符串爲空串,則返回空串
"string\r\n".chop #返回"string"
"string\n\r".chop #返回"string\n"
"string".chop #返回"strin"
"s".chop.chop #返回""str.chop!
--------------------------------------------------------------------------------
str.chomp(endstr)
#刪除str的後綴endstr
#若是未指定endstr,則刪除回車換行符(\r、\n和\r\n)
"hello\r\n".chomp #返回"hello"
"hello".chomp("lo")#返回"hel"
"hello".chomp("l") #返回"hello"str.chomp!
"hello".include? "lo"
rand(100000)
def newpass( len )
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
newpass = ""
1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
return newpass
end
str.length => integer
str.include? other_str #true or false
"hello".include? "lo" #=> true
"hello".include? "ol" #=> false
"hello".include? ?h #=> true
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"
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", "", ""]
======================================================================
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"
==========================================
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"
=================================
字符串的比較<,<=,>,>=實際上是四個方法,他們都會調用<=>這個方法,咱們能夠從新定義<=>來改變比較的行爲:
class String
alias old_compare <=>
def <=>(other)
a = self.dup
b = other.dup
a.gsub!(/[\,\.\?\!\:\;]/, "")
b.gsub!(/[\,\.\?\!\:\;]/, "")
a.gsub!(/^(a |an |the )/i, "")
b.gsub!(/^(a |an |the )/i, "")
a.strip!
b.strip!
a.old_compare(b)
end
end
title1 = "Calling All Cars"
title2 = "The Call of the Wild"
# 未重定義以前,如下結果會是yes,但如今,將變成no
if title1 < title2
puts "yes"
else
puts "no"
end
可是,==不會調用<=>,所以,若是咱們要定義特殊的「比較是否相等」,則咱們須要覆蓋==這個方法。