- 論壇徽章:
- 0
|
本帖最后由 zuerrong 于 2010-12-09 16:33 編輯
之所以說ruby字串為王,是因?yàn)閞uby是我所見過的語言里,字串處理最為強(qiáng)大的。
創(chuàng)建一個(gè)字串。任何字串都是String類的實(shí)例,所以也可以這樣創(chuàng)建:
字串可以用“<<”聯(lián)合起來:
irb(main):005:0> s << " world"
=> "hello world"
當(dāng)然可以串串燒:
irb(main):006:0> s << " welcome" << " to" << " ruby"
=> "hello world welcome to ruby"
字串跟數(shù)組一樣,可以使用下標(biāo)來訪問:
irb(main):007:0> s = "hello world"
=> "hello world"
irb(main):009:0> s[0].chr
=> "h"
還可以使用類似于slice的方法:
irb(main):010:0> s[0..3]
=> "hell"
irb(main):011:0> s[0,3]
=> "hel"
在數(shù)組里講過,這兩者是不同的,前者的3表示位置終結(jié)數(shù)字,后者的3表示長度。
更勝一籌的是,可以直接取出字串:
irb(main):013:0> s["hello"]
=> "hello"
而子串稱述更可以是正則表達(dá)式:
irb(main):014:0> s[/^\w+/]
=> "hello"
跟數(shù)組一樣,字串也支持insert方法:
irb(main):022:0> s= "prety"
=> "prety"
irb(main):023:0> s.insert(-2,"t")
=> "pretty"
表示在-2的位置,插入一個(gè)"t"。
修改字串在ruby里是如此方便,直接像數(shù)組一樣使用下標(biāo)即可:
irb(main):024:0> s = "nice girl"
=> "nice girl"
irb(main):025:0> s[0,4] = "helo"
=> "helo"
irb(main):026:0> s
=> "helo girl"
除了下標(biāo)還可以用正則表達(dá)式:
irb(main):032:0> s[/^\w+/] = "prety"
=> "prety"
irb(main):033:0> s
=> "prety girl"
字串的chop和chomp方法作用不同,前者刪除最后一個(gè)字符,后者刪除換行號(hào):
irb(main):034:0> "hello".chop
=> "hell"
irb(main):035:0> "hello\n".chomp
=> "hello"
去除字串兩邊空格:
irb(main):076:0> " abc ".strip
=> "abc"
去除左邊空格:
irb(main):077:0> " abc ".lstrip
=> "abc "
去除右邊空格:
irb(main):078:0> " abc ".rstrip
=> " abc"
還可以使用delete方法刪除字串里的字符:
irb(main):036:0> "hello".delete("l")
=> "heo"
最常用的字串操作方法包括gsub和scan,都支持正則表達(dá)式。
irb(main):037:0> s="hello world"
=> "hello world"
irb(main):038:0> s.gsub(/^\w+/,"kind")
=> "kind world"
irb(main):039:0> s.scan(/\w+/)
=> ["hello", "world"]
gsub執(zhí)行子串替換,把匹配到的內(nèi)容替換成第二個(gè)參數(shù)的內(nèi)容。
scan執(zhí)行字串查找,返回一個(gè)結(jié)果數(shù)組。
字串可以split成數(shù)組:
irb(main):044:0> s.split(//)
=> ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
split同樣支持正則表達(dá)式。
字串轉(zhuǎn)換成整數(shù)或浮點(diǎn):
irb(main):060:0> "123".to_i
=> 123
irb(main):061:0> "123".to_f
=> 123.0
each_byte可以遍歷一個(gè)字串:
irb(main):047:0> "matz".each_byte { |b| puts b.chr }
m
a
t
z
=> "matz"
顧名思義,downcase和upcase方法轉(zhuǎn)換大小寫:
irb(main):048:0> "I LOVE RUBY".downcase
=> "i love ruby"
irb(main):049:0> "I love Ruby".upcase
=> "I LOVE RUBY"
字串的長度:
irb(main):050:0> "hello".size
=> 5
字串還可以next:
irb(main):053:0> "x".next
=> "y"
irb(main):054:0> "xyz".next
=> "xza"
從a到z怎么遍歷呢?很簡(jiǎn)單:
irb(main):055:0> "a".upto("z") do |s| print s end
abcdefghijklmnopqrstuvwxyz=> "a"
ruby最強(qiáng)大的字串處理,莫過于跟perl一樣,內(nèi)置正則表達(dá)式。
irb(main):070:0> s = "hello ruby world"
=> "hello ruby world"
irb(main):071:0> s =~ /ruby/
=> 6
irb(main):072:0> s =~ /Ruby/
=> nil
正則表達(dá)式執(zhí)行后,返回的結(jié)果是匹配開始的位置,nil表示不匹配。
當(dāng)然,在ruby世界里很多人反過來寫:
irb(main):074:0> /ruby/ =~ s
=> 6
第一種寫法表示字串目標(biāo)支持=~方法,參數(shù)是正則表達(dá)式目標(biāo)。
第二種寫法表示正則表達(dá)式目標(biāo)支持=~方法,參數(shù)是字串目標(biāo)。
據(jù)說后者效率更高。
字串還有很多實(shí)用方法,運(yùn)行如下語句看看:
irb(main):075:0> String.instance_methods.sort |
|