Ruby字符串处理
2017-05-03 本文已影响0人
coloc
ruby字符串处理方法
截取
单个字符
>> s = "hello"
=> "hello"
>> s[0] # 第一个字符
=> "h"
>> s[s.length - 1] # 左边数字符串长度减1个,即最后一个字符,左边数下标从0开始
=> "o"
>> s[-1] # 右边数第一个字符
=> "o"
>> s[-s.length] # 右边数字符串长度个,即第一个字符
=> "h"
>> s[10] # 索引超出范围
=> nil
子串
>> s = "hello"
=> "hello"
>> s[2..3] # 位于索引2到3的字符
=> "ll"
>> s[-3..-1] # 可以使用负的索引值,代表从右向左
=> "llo"
>> s[0..0] # 第一个字符
=> "h"
>> s[0..1] # 前两个字符
=> "he"
>> s[2..1] # 起始索引大于结束索引,为空字符串
=> ""
>> s[7..10] # 索引超出范围
=> nil
替换
替换单个
>> s = "hello"
=> "hello"
>> s[0] = "H" # 将第一个字符替换为新字符
=> "H"
>> s
=> "Hello"
>> s[-2] = "L" # 将右边数第2个字符替换为新字符
=> "L"
>> s
=> "HelLo"
>> s[-1] = "UU" # 将右边数第1个字符替换为新字符集
=> "UU"
>> s
=> "HelLUU"
>> s[10] = "U" # 抛出异常,索引超出范围
IndexError: index 10 out of string
替换子集
>> s = "hello"
=> "hello"
>> s[-2..-1] = "pas" # 将从右数第2到第1个字符替换为新值
=> "pas"
>> s
=> "helpas"
>> s[0..0] = "please " # 将第一个字符替换为新值
=> "please "
>> s
=> "please elpas"
>> s[6..10] = "" # 将第6到10个字符替换为空值,即删除子串
=> ""
irb(main):029:0> s
=> "pleases"
包含
>> s = "hello"
=> "hello"
>> s["el"] # 测试是否包含子串,包含的情况
=> "el"
>> s["LL"] # 不包含的情况
=> nil
>> while(s["l"]) # 循环测试,将匹配到的所有子串替换为新值
>> s["l"]="L"
>> end
=> nil
>> s
=> "heLLo"