`
zarknight
  • 浏览: 146471 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Ruby way 第二章【字符串】

阅读更多
重定义字符串的比较
=================================
字符串的比较<,<=,>,>=其实是四个方法,他们都会调用<=>这个方法,我们可以

重新定义<=>来改变比较的行为:

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

但是,==不会调用<=>,因此,如果我们要定义特殊的“比较是否相等”,则我

们需要覆盖==这个方法。


切分字符串
===========================================================
默认的字符串切分符号是空格。
s1 = "It was a dark and stormy night."
words = s1.split          # ["It", "was", "a", "dark", "and",

"stormy", "night"]

也可以指定切分符:
s2 = "apples, pears, and peaches"
list = s2.split(", ")     # ["apples", "pears", "and peaches"]

s3 = "lions and tigers and bears"
zoo = s3.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"


未完...

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics