Ruby语言学习系列--String 类函数
函数名称 |
说明 |
示例 |
* |
将字符串拷贝N次 |
“ha”*4 >> “hahahaha” |
+ << concat |
连接字符串 |
“yes” + “no” >> “yesno” "yes" << "no" >> “yesno” "yes".concat("no") |
<=> |
比较字符串,返回值如下: 大于:-1 等于:0 小于:1 |
"Ab" <=> "ab" >> -1 "ab" <=> "ab" >> 0 "ab" <=> "Ab" >> 1 |
== 或 === |
判断两个对象是否相等 |
"1" == "1" >>true "1" == 1 >>flase |
=~ |
匹配正则表达式 |
"abc123abc" =~ /"d/ >> 3 |
[ ] 或 slice |
返回字符串的某一范围内的值 |
“abc”[0,2] >> “ab” "hello"[/llo/] >> “llo” “abc” slice [0,2] >> “ab” |
[ ]= |
替换字符串的某一范围内的值 |
a = “hello word” a[1,2]= “OO” puts a >>” hOOlo word” |
capitalize capitalize! |
把字符串的首字母大写,其他字母小写 |
"hi,Ruby".capitalize >> “Hi,ruby” |
chomp chomp! |
删除字符串后的空白字符 |
"string"r"n".chomp >> ” string” |
chop |
删除最后一个字符 |
"string".chop >> “strin” |
count |
返回该字符串中含的字符个数 |
a = "hello world" a.count "lo" >> 5 (l出现 3次,o出现 2次) |
delete delete! |
删除字符 |
"hello".delete "l","lo" » "heo" "hello".delete "lo" » "he" |
downcase downcase! |
将大写字母改写为小写 |
"hEllO".downcase » "hello" |
upcase upcase! |
将小写字母改写为大写 |
"hEllO".upcase » "HELLO" |
swapcase swapcase! |
将所有的大写字母改为小写字母, 小写字母改为大写字母。 |
"Hello".swapcase » "hELLO" |
each |
对字符串中的各行进行迭代操作 |
"Hi"nRuby". each { |s| puts s} |
each_byte |
对字符串中的各个字节进行迭代操作 |
"Hi"nRuby". each_byte { |s| puts s} |
each_line |
对字符串中的每一行进行迭代操作 |
"Hi"nRuby". each_line { |s| puts s} |
empty? |
判断字符串是否为空 |
"hello".empty? » false "".empty? » true |
gsub gsub! |
以replace来替换字符串中所有与pattern相匹配的部分 |
"hello".gsub(/[aeiou]/, '*') » "h*ll*" |
hash |
返回字符串的哈希值 |
"h".hash >> 107 |
include? |
若字符串中包含substr子字符串的话,就返回真 |
"hello".include? "lo" » true "hello".include? "ol" » false |
index |
按照从左到右的顺序搜索子字符串,并返回搜索到的子字符串的左侧位置. 若没有搜索到则返回nil |
"hello".index('lo') » 3 "hello".index('a') » nil |
length |
返回字符串的字节数 |
"hello".length >> 5 |
replace |
替换字符串的内容 |
s = "hello" » "hello" s.replace "world" » "world" |
sub 或 sub! |
用replace来替换首次匹配pattern的部分。 |
"hello".sub(/[aeiou]/, '*') » "h*llo" |
reverse reverse! |
对字符串进行反转 |
"stressed".reverse » "desserts" |
scan |
使用正则表达式re反复对 |
a = "cruel world" a.scan(/"w+/) » ["cruel", "world"] a.scan(/.../) » ["cru", "el ", "wor"] |
split |
使用sep指定的pattern来分割字符串,并将分割结果存入数组 |
"mellow yellow".split("ello") » ["m", "w y", "w"] |
squeeze squeeze! |
压缩由str所含字符构成的重复字符串 |
"yellow moon".squeeze » "yelow mon" " now is the".squeeze(" ") » " now is the" |
strip strip! |
删除头部和尾部的所有空白字符。空白字符是指" "t"r"n"f"v"。 |
" hello ".strip » "hello" ""tgoodbye"r"n".strip » "goodbye" |
tr 或tr! |
若字符串中包含search字符串中的字符时,就将其替换为replace字符串中相应的字符 |
hello".tr('aeiou', '*') » "h*ll*" "hello".tr('^aeiou', '*') » "*e**o" |
tr_s 或tr_s! |
若字符串中包含search字符串中的字符时,就将其替换为replace字符串中相应的字符。同时,若替换部分中出现重复字符串时,就将其压缩为1个字符 |
"hello".tr_s('l', 'r') » "hero" "hello".tr_s('el', '*') » "h*o" "hello".tr_s('el', 'hx') » "hhxo" |
在从 |
"a1".upto("a3") {|s| puts s} » a1"na2"na3 |
|
to_f |
将字符串转为浮点数 |
"45.67 degrees".to_f » 45.67 |
to_i |
将字符串转为整数 |
"99 red balloons".to_i » 99 |
to_s |
将字符串转为字符串 |
|