《Ruby 基础教程》之字符串类

118 阅读1分钟

字符串创建

当创建包含 " 或者 ' 的字符串时,比起使用 " 、 ' 进行转义,使用 %Q 或者 %q 会更简单。

desc = %Q{Ruby 的字符串中也可以使用 '' 和 ""。}
str = %q|Ruby said, 'Hello world!'|

使用 %Q 相当于用 " " 创建字符串,使用 %q 则相当于用 ' ' 创建字符串。

获取字符串的长度

p "just another ruby hacker,".length #=> 25
p "just another ruby hacker,".size #=> 25
p '面向对象编程语言 '.length #=> 8
p '面向对象编程语言 '.bytesize #=> 24
p "".empty? #=> true
p "foo".empty? #=> false

字符串的连接

hello = "Hello, "
world = "World!"
str = hello + world
p str #=> "Hello, World!"
hello << world
p hello #=> "Hello, World!"
hello.concat(world)
p hello #=> "Hello, World!World!"
hello = hello + world

用 + 连接原有字符串的结果会被再次赋值给变量 hello ,这与使用 << 的结果是一样的。但用 + 连接后的字符串对象是新创建的,并没有改变原有对象,因此即使有其他变量与 hello 同时指向原来的对象,那些变量的值也不会改变。而使用 << 与 concat 方法时会改变原有的对象,因此就会对指向同一对象的其他变量产生影响。

一般情况下使用 << 与 concat 方法会更加有效率,但是我们也应该根据实际情况来选择适当的字符串连接方法。

字符串的检索与替换

str = "ABBBBBB"
p str.index("BB") #=> 1
p str.rindex("BB") #=> 5
str = "ABBBBBB"
p str.include?("BB") #=> true
"hello".sub(/[aeiou]/, '*')                  #=> "h*llo"
"hello".gsub(/[aeiou]/, '*')                  #=> "h*ll*"

字符串方法

  • s[n] = str
    s[n..m] = str
    s[n, len] = str
    s.slice(n)
    s.slice(n..m)
    s.slice(n, len)
  • s.slice!(n)
    s.slice!(n..m)
    s.slice!(n, len)
  • s.concat(s2)
    s+s2
  • s.delete(str)
    s.delete!(str)
  • s.reverse
    s.reverse!
  • s.strip
    s.strip!
  • s.upcase
    s.upcase!
    s.downcase
    s.downcase!
    s.swapcase
    s.swapcase!
    s.capitalize
    s.capitalize!
  • s.tr
    s.tr!