ruby分割字符串_Ruby字符串

构建方法

str = 'hello world' # 只允许`\\`与`\'`转义

str = "hello world" # 允许所有转义和`#{}`字符串拼接

str = %q/hello world/ # 等同单引号

str = %Q{hello world} # 等同双引号

str=<

hello world

EOS

str = "abc" * 2 # => "abcabc"

索引

str = "abc"

s = str[-1] # s => 'c'

s1 = str[2] # s1 => 'c' ,ruby中的字符视为整数

s2 = str[1,2] # s2 => "bc" ,表示从1下标开始去长度2的两个字符

s3 = str[1..2] # s3 => "bc" ,下标从1取到2

操作方法

给定字符串str = "abc"

空字符吗

str.empty? # => false

长度

str.length # => 3

str.size # => 3

删除换行符

str.chop # => "ab" 无条件切除最后一个字符

str.chomp # => "abc" 若行末为换行符则删除

str1 = "abc\n"

str1.chomp # => "abc"

str1.chop # => "abc"

# 破坏性删除使用,str1.chomp! str1.chop!,即引用删除并返回

删除前后空白

str1 = " abc "

str1.strip # => "abc"

找指定字符串索引

str.index(a) # => 0,从左向右索引,索引从0开始

str.rindex(a) # => 3 ,从右向左索引,索引从1开始

包含指定子串吗

str.include? "ab" # => true

指定位置插入

str.insert(1,"dd") # => "addbc", 1下标字符前插入

str.insert(-1."dd") # => "abcdd", 倒数第n字符后插入

替换

##

# 用法

# str.gsub(pattern, replacement) => new_str

# str.gsub(pattern) {|match| block } => new_str

##

str.gsub(/[aeiou]/, '*') # => "*bc" #将元音替换成*号

str.gsub(/([aeiou])/, '') # => "bc" 将元音加上尖括号,\1表示匹配字符

str.gsub(/[aeiou]/) {|s| s + ' '} #=> "104 101 108 108 111 "

str.replace "abca" # str => "abca",重定义字符串

# 单次替换,用法与gsub相同,但仅替换第一次匹配

str1 = "aaaa"

str1.sub(/[aeiou]/,'d') # => "daaa"

删除

# 查询删除

str.delete "b" # => "ac",参数为字符串

# 索引方式删除

str.slice!(-1) == str.slice!(2) # => true

s = str.slice!(1,2) # s=> "a", 用法 => str.slice(index,len)

s1 = str.slice!(1..2) # s1 => "a", 用法 => str.slice!(index_begin..index_end)

分割为数组

str1 = "11:22:33:44"

column = str1.split(/:/) # column=> ["11", "22", "33", "44"]

翻转

str.reverse # => "cba"

大小写转换

str1 = str.upcase # str1 => "ABC"

str1.downcase # => "abc"

str.swapcase # => "ABC" 大写变小写,小写变大写

str.capitalize # => "Abc" 首字母大写,其余小写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值