显示标签为“downcase”的博文。显示所有博文
显示标签为“downcase”的博文。显示所有博文

2009年5月12日星期二

字符串的比较

使用 == 比较两个字符串的意思是否一样。



p '字符串' == '字符串'    #=> true
p '字符串' == '字符'    #=> false



大小写字母进行比较时,字母的大小写是有区别的。如果想无区分比较时,可以将两者 同时转化成大写或小写字母后在进行比较。大小写的转化使用 String#downcase



p 'ABC' == 'Abc'    #=> false
p 'ABC'.downcase == 'Abc'.downcase    #=> true



也可以不区分大小写对字母进行比较



$= = true
p 'ABC' == 'Abc'    #=> false



注:
    $= 这是一种过时的用法了(ruby1.8版本以前), 意思为除 nil 和 false 之外的任意值。如果一但设置此模式,所有匹配将于大小写无关,字符串比较将忽略大小写,而且字符串的 hash 值也会忽略大小写。(不推荐使用)

不仅如此,使用还可以使用 >, <, >=, <= 对字母的大小进行比较



p 'a' > 'b'    #=> false
p 'abc' < 'xyz'    #=> true

2009年5月6日星期三

ruby的字符型

单行字符串的输出:


str = 'hello the world'
p str    #=> "hello the world"
puts str    #=> hello the world



多行字符串的输出:


str = <<EOS
    This is test.
    Ruby, the Object Oriented Script Language.
EOS

puts str
    #=>This is test.
          Ruby, the Object Oriented Script Language.



字符串的结合:


str = 'hello'
puts str + ' the world'    #=> hello the world



字符串的追加:


str = 'hello'
str << ' the world'
puts str    #=> hello the world



生成重复的字符串:


str = 'hello '
puts str*3    #=> hello hello hello



大小写字母的变换:


str = 'I Love Ruby'
puts str.upcase    #=> I LOVE RUBY
puts str.downcase    #=> i love ruby



字符串中的部分字符的取得:


str = "Apple Banana Orange"
puts str[0..4]     #=> Apple
puts str[6, 6]     #=> Banana



字符串中的部分字符的置换:


str = "Apple Banana Apple Orange"
str[0..4] = "Vine"     #=> str = "Vine Banana Apple Orane"
str[5, 6] = "Lemon"     #=> str = "Vine Lemon Apple Orange"
str.sub("Apple", "Pine")     #=> str = "Pine Banana Apple Orange"
str.gsub("Apple", "Pine")     #=> str = "Pine Banana Pine Orange"



字符串中变数的展开:


value = 123
puts "value is #{value}"     #=> value is 123



字符串中方法的展开:


def sub(str)
    "Hello, #{str}."
end

puts "Say #{sub('Tomoya')}"     #=> Say Hello, Tomoya.



削除字符串头和尾的空格:


str = ' Hello, Ruby! '
p s.strip     #=> "Hello, Ruby!"




削除字符串尾部的换行:


str = 'Hello, Ruby!\n'
p str.chomp    #=> "Hello, Ruby!"
p str.strip    #=> "Hello, Ruby!"




字符型向数值型的转换:


str = '99'
i = 1
puts i + str.to_i    #=> 100



数值型向字符型的转换:


str = '99'
i = 1
p i.to_s + str    #=> "199"



字符型(数值型)向浮点小数型的转换:


str = '99'
puts str.to_f    #=> 99.0



下一个字符串的取得:


p "9".succ    #>= "10"
p "a".succ    #>= "b"
p "AAA".succ    #>= "AAB"
p "A99".succ    #>= "B00"
p "A099".succ    #>= "A100"



检查字符串中是否有相同字符出现:


str = "Apple Banana Apple Orange"

# 从左则开始查找 puts str.index("Apple")    #=> 0
puts str.index("Banana")    #=> 6
puts str.index("Apple", 6)    #=> 13

# 从右则开始查找 puts str.rindex("Apple")    #=> 13
puts str.rindex("Apple", 6)    #>= 0



字符串的居中,居左和居右:


str = "Ruby"
p str.center(10)     #=> " Ruby "
p str.ljust(10)    #=> "Ruby "
p str.rjust(10)    #=> " Ruby"