国产探花免费观看_亚洲丰满少妇自慰呻吟_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.去掉前和后的空格

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 台北市| 建阳市| 县级市| 平南县| 怀远县| 洛川县| 织金县| 即墨市| 永和县| 绵竹市| 怀仁县| 徐水县| 梁河县| 南宫市| 兴海县| 花莲县| 屯留县| 鸡东县| 昌平区| 木里| 浑源县| 清丰县| 开化县| 呈贡县| 桂东县| 车致| 广州市| 渝中区| 巴青县| 拉萨市| 武威市| 隆化县| 土默特右旗| 柘城县| 沐川县| 林西县| 钟祥市| 刚察县| 房产| 永定县| 广元市|