Ruby 学习(五)字符串String

String

''""

  • 单引号标记: 不允许替换,且只允许使用 \\\ 两个反斜线符号。
  • 双引号标记: 允许替换和使用反斜线符号,支持更多的转义字符

#{ expr } 双引号的字符串才可以使用

  • 可以使用序列 #{ expr } 替换任意 Ruby 表达式的值为一个字符串。
  • 在这里,expr 可以是任意的 Ruby 表达式。
text = "hello world"
text1 = "#{text + ' new'}"

print text1
# 输出 hello world new

多行字符串

"Here Document" 是指建立多行字符串。在 << 之后,您可以指定一个字符串或标识符来终止字符串,且当前行之后直到终止符为止的所有行是字符串的值。

如果终止符用引号括起,引号的类型决定了面向行的字符串类型。请注意<< 和终止符之间必须没有空格。

print <<EOF
    这是第一种方式创建here document 。
    多行字符串。
EOF
text = <<EOF
这是第一种方式创建here document 。
多行字符串。
EOF

print text

字符编码

取值含义
aASCII (与 none 相同)。这是默认的。
eEUC。
nNone (与 ASCII 相同)
uUTF-8。

在程序的开头改变字符集 $KCODE
注意:这个已经不使用了

$KCODE = 'u'

程序运行的时候会有如下的错误

warning: variable $KCODE is no longer effective; ignored

常用 api

大小

str.length

str = "Hello"

puts str.length # 5

str.empty?

是否为空

str = "Hello"

puts str.empty? # false

str * integer

把字符串 str 重复 integer

str = "one "

puts str * 3
one one one 

拼接

str + other_str

字符串拼接

str = "one"

puts str + "two"
onetwo

str.concat(other_str)

str = "hello"

puts str.concat(" world!") # hello world!

比较

相等判断 str <=> other_str

字符串比较,比较是区分大小写的

  • 小于:-1
  • 等于:0
  • 大于:1()

相等判断 str == obj

相等性比较

  • 如果 obj 不是字符串,则返回 false,
  • 如果 str <=> obj,则返回 true,返回 0。

相等判断 str.eql?(other)

str = "Hello"

puts str.eql?("hello") # false
puts str.eql?("Hello") # true
puts str.eql?("123") # false

str =~ obj

  • 根据正则表达式模式 obj 匹配 str。
  • 返回匹配开始的位置,否则返回 false。

字符串截取

# 注意返回的是ASCII码而不是字符
str[position]

str[start, length]

str[start..end]

str[start...end]
str = "hello world!"

puts str[1] # e
puts str[1, 2] # el
puts str[1..3] # ell
puts str[1...3] # el

大小写

首字母大写 str.capitalize str.capitalize!

str = "hello"

puts str.capitalize # Hello

小写字母 str.downcase str.downcase!

str = "Hello"

puts str.downcase # hello

大写 str.upcase str.upcase!

str = "Hello"

puts str.upcase # HELLO

大小写转换 str.swapcase str.swapcase!

str = "Hello"

puts str.swapcase # hELLO

str.chop

移除最后一个字符

str = "hello"

puts str.chop # hell

替换 str.replace(other_str)

str = "Hello"

puts str.replace("new hello") # new hello

反转 str.reverse str.reverse!

str = "Hello"

puts str.reverse # olleH
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值