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"

没有评论:

发表评论