字符串处理函数
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.去掉前和后的空格

str.lstrip => new_str
" hello ".lstrip #=> "hello "
"hello".lstrip #=> "hello"

8.字符串匹配

str.match(pattern) => matchdata or nil

9.字符串反转

str.reverse => new_str
"stressed".reverse #=> "desserts"

10.去掉重复的字符

str.squeeze([other_str]*) => new_str
"yellow moon".squeeze #=> "yelow mon" #默认去掉串中所有重复的字符
" now is the".squeeze(" ") #=> " now is the" #去掉串中重复的空格
"putters shoot balls".squeeze("m-z") #=> "puters shot balls" #去掉指定范围内的重复字符

11.转化成数字

str.to_i=> str
"12345".to_i #=> 12345

chomp和chop的区别:
chomp:去掉字符串末尾的\n或\r
chop:去掉字符串末尾的最后一个字符,不管是\n\r还是普通字符

"hello".chomp            #=> "hello"
"hello\n".chomp #=> "hello"
"hello\r\n".chomp #=> "hello"
"hello\n\r".chomp #=> "hello\n"
"hello\r".chomp #=> "hello"
"hello".chomp("llo") #=> "he" "string\r\n".chop #=> "string"
"string\n\r".chop #=> "string\n"
"string\n".chop #=> "string"
"string".chop #=> "strin"
 

split是String类一个类方法,我根据ri String.split提供的内容简单翻译一下。

----------------------------------------------------------- String#split

str.split(pattern=$;, [limit])       => anArray

------------------------------------------------------------------------

Divides _str_ into substrings based on a delimiter, returning an

array of these substrings.

将一个字符串用分隔符分割成一些子字符串,并返回一个包含这些子字符串的数组。

If _pattern_ is a +String+, then its contents are used as the

delimiter when splitting _str_. If _pattern_ is a single space,

_str_ is split on whitespace, with leading whitespace and runs of

contiguous whitespace characters ignored.

如果pattern部分一个字符串,那么用它作分割符来分隔,如果pattern是一个空格,那么在空格处分割,并且临近的空格被忽略。

If _pattern_ is a +Regexp+, _str_ is divided where the pattern

matches. Whenever the pattern matches a zero-length string, _str_

is split into individual characters.

如果pattern是个正则达式,那么在匹配pattern的地方分割,当pattern是长度为0的字符串,那么split将把字符串分割为单个字符

If _pattern_ is omitted, the value of +$;+ is used. If +$;+ is

+nil+ (which is the default), _str_ is split on whitespace as if `

' were specified.

如果pattern被忽略,将用$;来分隔,如果$;没有设置(就是在默认状态),split将制定空格' '

If the _limit_ parameter is omitted, trailing null fields are

suppressed. If _limit_ is a positive number, at most that number of

fields will be returned (if _limit_ is +1+, the entire string is

returned as the only entry in an array). If negative, there is no

limit to the number of fields returned, and trailing null fields

are not suppressed.

如果limit参数被忽略,跟踪空段被抑制,如果limit是个正数,那么至多返回limit个字段(如果是1,那么将整个字符串作为一个字段返回),如果是个负数,那么跟踪空段不被抑制。

" now's      the time".split            #=> ["now's", "the", "time"]

" now's      the time".split(' ')       #=> ["now's", "the", "time"]

" 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,,"]

"1,2,,3,4,,".split(',', -4)         #=> ["1", "2", "", "3", "4", "", ""]

如果包含特殊字符,注意转义

"wo | shi | yi | ge | bing".split(/\s*\|\s*)              #竖杠别忘了转义

还有它和String.scan的区别,split中的pattern是分隔符,而scan中的pattern指的是要匹配的东西。

"123=342=4234=523421=6424".scan(/\d+/)     #=>     ["123","342","4234","523421","6424"]

如果匹配项被括起来,那么则会保留分割符,例如:

"Three little words".split(/\s+/)    #===>["three","little",words"]

"Three little words".split(/(\s+)/)      #===>["three"," ","little"," ","words"]    保留了空格

Ruby:字符串处理函数的更多相关文章

  1. Python:字符串处理函数

    split() / join() 拆分和组合 #split() 通过指定分隔符对字符串进行切片(拆分),默认空格符 lan = "python ruby c c++ swift" ...

  2. VB常用字符串操作函数

    1. ASC(X),Chr(X):转换字符字符码 [格式]: P=Asc(X) 返回字符串X的第一个字符的字符码 P=Chr(X) 返回字符码等于X的字符 [范例]: (1)P=Chr(65) ‘ 输 ...

  3. php-设置关键词高亮的字符串处理函数

    /** * 设置关键词高亮的字符串处理函数 * @param [string] $str [要高亮的字符串] * @param array $word_arr [关键词] */function set ...

  4. JS字符串格式化函数 string.format

    原生JS写的仿C#的字符串format函数,在此基础上又增加了便于JS使用的字面量对象参数. 参照C#中的规则,调用的时候会检测字符串格式,如果字符串格式不规范,或者传入的参数为null或undefi ...

  5. JS字符串替换函数:Replace(“字符串1″, “字符串2″),

    JS字符串替换函数:Replace(“字符串1″, “字符串2″), 1.我们都知道JS中字符串替换函数是Replace(“字符串1″, “字符串2″),但是这个函数只能将第一次出现的字符串1替换掉, ...

  6. Excel怎样从一串字符中的某个指定“字符”前后截取字符及截取字符串常用函数

    怎么样可以从一串字符中的某个指定位置的前或后截取指定个数的字符. 如:12345.6789,我要截取小数点前(或后)的3个字符.怎么样操作, 另外,怎么样从右边截取字符,就是和left()函数相反的那 ...

  7. SQL注入的字符串连接函数

    在select数据时,我们往往需要将数据进行连接后进行回显.很多的时候想将多个数据或者多行数据进行输出的时候,需要使用字符串连接函数.在sqli中,常见的字符串连接函数有concat(),group_ ...

  8. C语言字符串处理函数

    函数名: strcpy  功  能: 拷贝一个字符串到另一个  用  法: char *stpcpy(char *destin, char *source);  程序例:  #include < ...

  9. JavaScript中常见的字符串操作函数及用法

    JavaScript中常见的字符串操作函数及用法 最近几次参加前端实习生招聘的笔试,发现很多笔试题都会考到字符串的处理,比方说去哪儿网笔试题.淘宝的笔试题等.如果你经常参加笔试或者也是一个过来人,相信 ...

随机推荐

  1. EF 底层基础方法

    1 using System; 2 using System.Data; 3 using System.Collections.Generic; 4 using System.Data.Entity; ...

  2. Backbone框架浅析

    Backbone是前端mvc开发模式的框架.它能够让view和model相分离,让代码结构更清晰简答,开发进度加快,维护代码方便.但是,现在出了一种mvvm框架,它是下一代前端mvc开发模式的框架,代 ...

  3. NPOI Helper文档

    public class ExcelHelper { /// <summary> /// NPOI Excel转DataTable /// </summary> /// < ...

  4. PRML

    PRML 学习之 第一章 介绍 Introduction #欢迎共同学习和讨论,由于本文将不断修改,谢绝转载 模式识别问题具有重要且久远的历史.比如,16世纪开普勒发现行星运动定律,又如20世纪出发现 ...

  5. 使用MLeaksFinder检测项目中的内存泄露

    github地址:https://github.com/Zepo/MLeaksFinder MLeaksFinder使用简单方便,可以帮助你在开发时发现内存泄露你的iOS应用.它可以自动发现和UIVi ...

  6. Python2.7如何安装numhttp://www.cnblogs.com/yuanzm/p/4089856.htmlpy

    numpy是python一个函数库,做数据挖掘是很好的.但是一般是不带这个函数库的,所以接下来我要讲下如何安装这个函数库, 首先有一种方法是: 傻瓜式安装法:https://sourceforge.n ...

  7. Tomasulo's Algorithm

    如果操作数在寄存器中,将会存在V字段,否则,设置Q字段来指示reservation station将会产生运算所需要的操作数 reorder buffer包含4个字段 the instruction ...

  8. java.sql.SQLException: ORA-00911: invalid character 解决方法

    java.sql.SQLException: ORA-00911: invalid character 控制台抛出这个异常:java.sql.SQLException: ORA-00911: inva ...

  9. 利用Unity制作“表”

    一枚小菜鸟   目前没发现在Unity有其他路径制作类似于c# WinForm中的表:但是利用Unity自带的UGUI,制作了一张"伪表",具体方案如下: 效果图如下: 步骤: 1 ...

  10. jquery制作省份城市地区多选控件总结

    1.弹出的选择框有jquery直接放在body后面,以position:absolute绝对定位,top,left处理位置. 如果想让该选择框位于点选元素下面,则获取点选元素位置 var target ...