国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Ruby中常用的字符串處理函數使用實例

2019-10-26 19:24:57
字體:
來源:轉載
供稿:網友

1.返回字符串的長度
代碼如下:
str.length => integer

2.判斷字符串中是否包含另一個串
代碼如下:
str.include? other_str => true or false
"hello".include? "lo"   #=> true
"hello".include? "ol"   #=> false
"hello".include? ?h     #=> true

3.字符串插入
代碼如下:
str.insert(index, other_str) => str
"abcd".insert(0, 'X')    #=> "Xabcd"
"abcd".insert(3, 'X')    #=> "abcXd"
"abcd".insert(4, 'X')    #=> "abcdX"
"abcd".insert(-3, 'X')
-3, 'X')   #=> "abXcd"
"abcd".insert(-1, 'X')   #=> "abcdX"

4.字符串分隔,默認分隔符為空格
代碼如下:
str.split(pattern=$;, [limit]) => anArray
" now's the time".split        #=> ["now's", "the", "time"]
"1, 2.34,56, 7".split(%r{,/s*}) #=> ["1", "2.34", "56", "7"]
"hello".split(//)               #=> ["h", "e", "l", "l", "o"]
"hello".split(//, 3)            #=> ["h", "e", "llo"]
"hi mom".split(%r{/s*})         #=> ["h", "i", "m", "o", "m"]
"mellow yellow".split("ello")   #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]

5.字符串替換
代碼如下:
str.gsub(pattern, replacement) => new_str
str.gsub(pattern) {|match| block } => new_str
"hello".gsub(/[aeiou]/, '*')              #=> "h*ll*"     #將元音替換成*號
"hello".gsub(/([aeiou])/, '</1>')         #=> "h<e>ll<o>"   #將元音加上尖括號,/1表示保留原有字符???
"hello".gsub(/./) {|s| s[0].to_s + ' '}   #=> "104 101 108 108 111 "

字符串替換二:
代碼如下:
str.replace(other_str) => str
s = "hello"         #=> "hello"
s.replace "world"   #=> "world"

6.字符串刪除
代碼如下:
str.delete([other_str]+) => new_str
"hello".delete "l","lo"        #=> "heo"
"hello".delete "lo"            #=> "he"
"hello".delete "aeiou", "^e"   #=> "hell"
"hello".delete "ej-m"          #=> "ho"

7.去掉前和后的空格

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 开封市| 盐亭县| 绵竹市| 建德市| 通榆县| 白朗县| 汪清县| 西充县| 饶阳县| 交城县| 麟游县| 天气| 秦安县| 临潭县| 怀仁县| 伽师县| 宁南县| 汪清县| 田阳县| 合肥市| 乐都县| 乡宁县| 六枝特区| 新昌县| 博客| 英吉沙县| 北碚区| 康平县| 吉木乃县| 安乡县| 景洪市| 永清县| 兴和县| 嘉善县| 卓尼县| 舒兰市| 罗定市| 于田县| 榆社县| 湟中县| 达州市|