---
title: "ruby字符串操作"
author: "rloc2003"
date: "2011-10-18T11:06:00Z"
tags: []
categories: ["Web前端"]
slug: "ruby"
draft: false
lastmod: "2011-10-18T11:06:00Z"
id: 1199063
url: "https://rloc2003.iteye.com/blog/1199063"
---

1.返回字符串的长度

str.length =&gt; integer

 

2.判断字符串中是否包含另一个串

str.include? other\_str =&gt; true or false

"hello".include? "lo" #=&gt; true

"hello".include? "ol" #=&gt; false

"hello".include? ?h #=&gt; true

 

3.字符串插入:

str.insert(index, other\_str) =&gt; str

"abcd".insert(0, 'X') #=&gt; "Xabcd"

"abcd".insert(3, 'X') #=&gt; "abcXd"

"abcd".insert(4, 'X') #=&gt; "abcdX"

"abcd".insert(-3, 'X') #=&gt; "abXcd"

"abcd".insert(-1, 'X') #=&gt; "abcdX"

 

4.字符串分隔,默认分隔符为空格

str.split(pattern=$;, \[limit]) =&gt; anArray

" now's the time".split #=&gt; \["now's", "the", "time"]

"1, 2.34,56, 7".split(%r{,\\s\*}) #=&gt; \["1", "2.34", "56", "7"]

"hello".split(//) #=&gt; \["h", "e", "l", "l", "o"]

"hello".split(//, 3) #=&gt; \["h", "e", "llo"]

"hi mom".split(%r{\\s\*}) #=&gt; \["h", "i", "m", "o", "m"]

"mellow yellow".split("ello") #=&gt; \["m", "w y", "w"]

"1,2,,3,4,,".split(',') #=&gt; \["1", "2", "", "3", "4"]

"1,2,,3,4,,".split(',', 4) #=&gt; \["1", "2", "", "3,4,,"]

 

5.字符串替换

str.gsub(pattern, replacement) =&gt; new\_str

str.gsub(pattern) {|match| block } =&gt; new\_str

"hello".gsub(/\[aeiou]/, '\*') #=&gt; "h\*ll\*" #将元音替换成\*号

"hello".gsub(/(\[aeiou])/, '') #=&gt; "h&lt;e&gt;ll&lt;o&gt;" #将元音加上尖括号,\\1表示保留原有字符???

"hello".gsub(/./) {|s| s\[0].to\_s + ' '} #=&gt; "104 101 108 108 111 "字符串替换二:

str.replace(other\_str) =&gt; str

s = "hello" #=&gt;"hello"

s.replace "world" #=&gt;"world"

 

6.字符串删除:

str.delete(\[other\_str]+) =&gt; new\_str

"hello".delete "l","lo" #=&gt; "heo"

"hello".delete "lo" #=&gt; "he"

"hello".delete "aeiou", "^e" #=&gt; "hell"

"hello".delete "ej-m" #=&gt; "ho"

 

7.去掉前和后的空格

str.lstrip =&gt; new\_str

" hello ".lstrip #=&gt; "hello "

"hello".lstrip #=&gt; "hello"

 

8.字符串匹配str.match(pattern) =&gt; matchdata or nil

 

9.字符串反转

str.reverse =&gt; new\_str

"stressed".reverse #=&gt; "desserts"

 

10.去掉重复的字符

str.squeeze(\[other\_str]\*) =&gt; new\_str

"yellow moon".squeeze #=&gt; "yelow mon" #默认去掉串中所有重复的字符

" now is the".squeeze(" ") #=&gt;" now is the" #去掉串中重复的空格

"putters shoot balls".squeeze("m-z") #=&gt; "puters shot balls" #去掉指定范围内的重复字符

 

11.转化成数字

str.to\_i=&gt; str "12345".to\_i #=&gt; 12345

chomp和chop的区别:chomp:去掉字符串末尾的\\n或\\r chop:去掉字符串末尾的最后一个字符,不管是\\n\\r还是普通字符"hello".chomp #=&gt; "hello"

"hello\\n".chomp #=&gt; "hello"

"hello\\r\\n".chomp #=&gt; "hello"

"hello\\n\\r".chomp #=&gt; "hello\\n"

"hello\\r".chomp #=&gt;"hello"

"hello".chomp("llo") #=&gt;"he"

"string\\r\\n".chop #=&gt; "string"

"string\\n\\r".chop #=&gt; "string\\n"

"string\\n".chop #=&gt; "string"

"string".chop #=&gt; "strin"

"x".chop.chop #=&gt; ""&lt;/o&gt;&lt;/e&gt;