Ruby字符串的一些方法

最近因为公司需求开始看ruby,先从ruby的基本数据类型开始看

看到ruby的字符串类型string,发现ruby中的字符串单双引号是不一样的,这点和Python有那么点不一样

主要是我们对字符串进行变量引用的时候要使用双引号

如下:

可支持全部的转义字符及用#{exp}将Ruby中的值插入字符串中

例:

i = 5

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

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

这是最大的区别

现在来看看ruby中字符串的方法:

1. 遇到\会进行转义

2.2.1 :041 > puts "daad\'"
daad'
 => nil 
2.2.1 :042 > puts "daad\\"
daad\
 => nil 

2. + 可以将字符串连接起来

例:

2.2.1 :043 > 'abc'+'def'
 => "abcdef" 

3. 字符串的内容重复times次

例:

2.2.1 :043 > 'abc'+'def'
 => "abcdef" 

4. 返回字符串的长度

length,size

例:

2.2.1 :052 >   str = "123456789"
 => "123456789" 
2.2.1 :054 > str.length
 => 9 
2.2.1 :055 > str.size
 => 9 

5.判断字符串中是否包含另一个字符串

str.include? other_str => true or false

例:

2.2.1 :060 > 'ruby'.include?'ru'
 => true 
2.2.1 :061 > 'ruby'.include?'pp'
 => false 

6.字符串的插入

str.insert(index, other_str)=> str

2.2.1 :062 > 'ruby'.insert(0,'add')    # 在索引为0的位置插入a,索引从0开始
 => "addruby" 
2.2.1 :063 > 'ruby'.insert(-1,'add')    #从最后一个索引开始添加
 => "rubyadd" 

7.字符串分割,默认分隔符为空格

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

和python差不多

例:

2.2.1 :065 > 'ruby abc def'.split      # 默认是一个空格符
 => ["ruby", "abc", "def"] 
2.2.1 :066 > 'ruby abc def'.split('a')
 => ["ruby ", "bc def"] 
2.2.1 :067 > 'ruby abc def'.split('',4)
 => ["r", "u", "b", "y abc def"] 
2.2.1 :068 > 'ruby abc def'.split(' ',4)
 => ["ruby", "abc", "def"] 

8.字符串的替换

str.sub(patternreplace)                          str.gsub(patternreplace)

str.sub!(patternreplace)                                                           str.gsub!(patternreplace)

str.sub(pattern) {|matched| ... }                                                        str.gsub(pattern){|matched| ... }

str.sub!(pattern) {|matched| ...}                                             str.gsub!(pattern){|matched| ... }

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”

9、 字符串删除

str.delete([other_str]+) => new_str   #删除参数交集出现的所有字符,返回一个新字符串

str. delete! ([other_str]+) => str   #原字符串会被改变

2.2.1 :078 > 'hello'.delete 'l'
 => "heo" 
2.2.1 :079 > 'hello'.delete 'l','lo'
 => "heo" 
2.2.1 :080 > 'hello'.delete 'lo'
 => "he" 

10. 去掉空白

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"

11.字符串匹配

str.match(pattern)=> matchdata or nil

例:

2.2.1 :093 > 'hello'.match(/l+/)
=> #<MatchData "ll">
2.2.1 :094 > 'hello'.match(/\w+/)
=> #<MatchData "hello">

12.字符串反转

str.reverse => new_str

str.reverse! => str # str本身会发生改变

2.2.1 :095 > 'hello'.reverse
 => "olleh" 

13.去掉重复的字符

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 " #去掉指定范围内的重复字符

 

14、字符串转化为数字

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

15、 删除字符串最后的字符

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

16、 格式化字符串

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      #返回原字符串的拷贝

17. 控制字符串的大小写

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"

18.字符串的匹配

“=~”:与正则表达式的匹配           

例:

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] 

字符串与正则相关的方法还有match和scan,match返回第一个匹配对象,scan返回所有符合正则表达式的数组

例:

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

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

19.字符串的子串

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

猜你喜欢

转载自www.cnblogs.com/Stay-J/p/9236190.html