设为首页 加入收藏

TOP

Ruby字符串(2):String方法详细整理(五)
2019-08-15 00:10:18 】 浏览:365
Tags:Ruby 字符串 String 方法 详细 整理
uot; "hello\r\n\r\n".chomp('') #=> "hello" "hello\r\n\r\r\n".chomp('') #=> "hello\r\n\r"

chop和chop!

chop → new_str
chop! → str or nil

移除字符串的最后一个字符。

如果字符串是空字符串,则chop直接返回一个空字符串,而chop!返回nil。

"string\r\n".chop   #=> "string"
"string\n\r".chop   #=> "string\n"
"string\n".chop     #=> "string"
"string".chop       #=> "strin"
"x".chop.chop       #=> ""

chr返回首字符

chr → string

返回字符串的首字符。

a = "abcde"
a.chr    #=> "a"

"我是单身狗".chr  #=> "我"

clear

clear → string

清空字符串。注意是原地修改的。

a = "abcde"
a.clear    #=> ""
a          #=> ""

count

count([other_str]+) → integer

从字符串中搜索给定字符的数量。多个other_str参数的交集确定要搜索的字符。支持^取反语义以及-取范围。如果要搜索这两个特殊字符本身,使用反斜线转义。

a = "hello world"
a.count "lo"                   #=> 5
a.count "lo", "o"              #=> 2,2个o
a.count "lo", "l"              #=> 3,3个l
a.count "hello", "^l"          #=> 4,heo共四个
a.count "ej-m"                 #=> 4,el共四个

"hello^world".count "\\^aeiou" #=> 4,^eo共4个
"he-llo-wor-ld".count "a\\-eo" #=> 6,-eo共6个

c = "hello world\\r\\n"
c.count "\\"                   #=> 2
c.count "\\A"                  #=> 0
c.count "X-\\w"                #=> 3

delete和delete!

delete([other_str]+) → new_str
delete!([other_str]+) → str or nil

删除字符串中的某些字符,返回删除后的字符串。

对于delete!,如果没有字符要删除,则返回nil。

other_str的规则和countother_str规则一致。

"hello".delete "l","lo"        #=> "heo"
"hello".delete "lo"            #=> "he"
"hello".delete "aeiou", "^e"   #=> "hell"
"hello".delete "ej-m"          #=> "ho"

delete_prefix和delete_prefix!

delete_suffix和delete_suffix!

delete_prefix(prefix) → new_str
delete_prefix!(prefix) → self or nil

delete_suffix(suffix) → new_str
delete_suffix!(suffix) → self or nil

从字符串头部或者字符串尾部删除指定的前缀、后缀。

如果没有需要删除的内容,对于delete_xxx,返回内容相同的新对象,对于delete_xxx!,则返回nil。

迭代each_xxx

包括each_byte、each_char、each_codepoint、each_line。

参见:字符串的迭代

up_to

upto(other_str, exclusive=false) {|s| block } → str
upto(other_str, exclusive=false) → an_enumerator

看例子:

"a8".upto("b6") {|s| print s, ' ' }
    #=> a8 a9 b0 b1 b2 b3 b4 b5 b6

for s in "a8".."b6"
  print s, ' '
end
    #=> a8 a9 b0 b1 b2 b3 b4 b5 b6
"9".upto("11").to_a   #=> ["9", "10", "11"]
"25".upto("5").to_a   #=> []
"07".upto("11").to_a  #=> ["07", "08", "09", "10", "11"]

empty?

empty? → true or false

判断字符串是否为空字符串。

"hello".empty?   #=> false
" ".empty?       #=> false
"".empty?        #=> true

encoding

encoding → encoding

返回字符串所使用的编码对象(Encoding Object)。

从此也可以知道所使用的是哪个编码。

>> var = "hello world"
>> var.encoding         #=> #<Encoding:UTF-8>
>> var.encoding.to_s    #=> "UTF-8"

encode和encode!

(1) encode(encoding [, options] ) → str
(2) encode(dst
首页 上一页 2 3 4 5 6 7 8 下一页 尾页 5/11/11
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇猫眼电影练习,动态字体 下一篇安装Ruby、多版本Ruby共存、Ruby..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目