字符串处理函数
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. 微信公众平台开发 微信JSSDK开发

    根据微信开发文档步骤如下: 1.先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”. JS接口安全域名设置 mi.com(前面不用带www/http,域名必须备案过) 2.引 ...

  2. 打造一个有感觉的vim(四)

    今天要介绍的VIM插件的名字叫做surround,这个插件的主要作用是将一个VIM的tex-objects(文本对象)添加或者取消包裹(单引号,双引号,XML标签等等)下载地址如下:https://g ...

  3. fiddler抓取Android 真机app数据包

    fiddler功能强大 不仅能抓pc上的请求还能抓取手机上的请求.下面以fiddler4 +android手机为例介绍一下 手机抓包. 官网下载fiddler后下一步下一步安装成功. 首先是fiddl ...

  4. 2016 ICPC China-Final 现场赛总结

    距离比赛结束快有一个礼拜了才抽出时间来写这篇总结.今年比赛打了也有5场了(4场区域赛+1场省赛),也取得了不错的成绩(区域赛两银),总的来说第一年就取得这成绩还是挺高兴的.我们队,我自己都渐渐的趋于成 ...

  5. 利用 cookie 模拟网站登录

    import urllib import urllib2 import cookielib filename = 'cookie.txt' \#声明一个MozillaCookieJar对象实例来保存c ...

  6. asp.net LINQ防止SQL注入式攻击

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  7. spring mvc 4.3.2 + mybatis 3.4.1 + mysql 5.7.14 +shiro 幼儿园收费系统 之 消息管理

  8. Git命令学习摘要

    1.git init  --初始化git项目 2.git status --查看项目的状态 3.git add filename --添加文件到项目 4.git diff filename --查看工 ...

  9. 【经验】ansible 批量推送公钥

    1.使用 ssh-keygen -t rsa生成密钥对 ssh-keygen -t rsa 2.推送单个公钥到远程机器 格式: ssh-copy-id -i ~/.ssh/id_rsa.pub use ...

  10. Robotium-无源码测试

    [总结] 1.新建工程,选择Android Application Project,选择This Project: PS:新建测试工程时报NULL错误,新建一个Android工程,然后再按上诉步骤建立 ...