美文网首页
Ruby字符串

Ruby字符串

作者: jerehao | 来源:发表于2016-11-13 15:08 被阅读0次

构建方法

str = 'hello world'        # 只允许`\\`与`\'`转义
str = "hello world"       # 允许所有转义和`#{}`字符串拼接
str = %q/hello world/      # 等同单引号
str = %Q{hello world}       # 等同双引号
str=<<EOS
    hello world
EOS

str = "abc" * 2        # => "abcabc"

索引

str = "abc"
s = str[-1]       # s => 'c'
s1 = str[2]        # s1 => 'c' ,ruby中的字符视为整数
s2 = str[1,2]     # s2 => "bc" ,表示从1下标开始去长度2的两个字符
s3 = str[1..2]     # s3 => "bc" ,下标从1取到2

操作方法

给定字符串str = "abc"

空字符吗

str.empty?   # => false

长度

str.length                            # => 3
str.size                               # => 3

删除换行符

str.chop # => "ab"   无条件切除最后一个字符
str.chomp # => "abc"  若行末为换行符则删除
str1 = "abc\n"
str1.chomp   # => "abc"
str1.chop # => "abc"
# 破坏性删除使用,str1.chomp!  str1.chop!,即引用删除并返回 

删除前后空白

str1 = " abc   "
str1.strip     # => "abc"

找指定字符串索引

str.index(a)    # => 0,从左向右索引,索引从0开始
str.rindex(a)   # => 3 ,从右向左索引,索引从1开始

包含指定子串吗

str.include? "ab"                         # => true  

指定位置插入

str.insert(1,"dd")                        # => "addbc", 1下标字符前插入
str.insert(-1."dd")                       # => "abcdd", 倒数第n字符后插入

替换

##
# 用法
# str.gsub(pattern, replacement) => new_str
# str.gsub(pattern) {|match| block } => new_str
##
str.gsub(/[aeiou]/, '*')                   # => "*bc" #将元音替换成*号
str.gsub(/([aeiou])/, '<\1>')           # => "<a>bc"  将元音加上尖括号,\1表示匹配字符
str.gsub(/[aeiou]/) {|s| s + ' '} #=> "104 101 108 108 111 "
str.replace "abca"                    # str => "abca",重定义字符串
# 单次替换,用法与gsub相同,但仅替换第一次匹配
str1 = "aaaa"
str1.sub(/[aeiou]/,'d')                           # => "daaa"

删除

# 查询删除
str.delete "b"                             # => "ac",参数为字符串
# 索引方式删除
str.slice!(-1) == str.slice!(2)      # => true
s = str.slice!(1,2)        # s=> "a", 用法 => str.slice(index,len)
s1 = str.slice!(1..2)     # s1 => "a", 用法 => str.slice!(index_begin..index_end)

分割为数组

str1 = "11:22:33:44"
column = str1.split(/:/) # column=> ["11", "22", "33", "44"] 

翻转

str.reverse # => "cba"

大小写转换

str1 = str.upcase   # str1 => "ABC"
str1.downcase    # => "abc"
str.swapcase  # => "ABC" 大写变小写,小写变大写
str.capitalize  # => "Abc" 首字母大写,其余小写

相关文章

  • ruby 数据类型

    1. Ruby 字符串(String) 2. Ruby 数组 3. Ruby 哈希 哈希的内置方法 4. Ruby...

  • ruby字符串

    Ruby 中的 String 对象用于存储或操作一个或多个字节的序列。 Ruby 字符串分为单引号字符串(')和双...

  • Ruby字符串(string)

    Ruby 中的 String 对象用于存储或操作一个或多个字节的序列。 Ruby 字符串分为单引号字符串(')和双...

  • 2016-11-04 task-list

    今日任务 ruby on rails 第四章 ruby 元编程 今日总结 ruby 单引号与双引号字符串的重大区别...

  • Ruby 字符串

  • Ruby字符串

    构建方法 索引 操作方法 给定字符串str = "abc" 空字符吗 长度 删除换行符 删除前后空白 找指定字符串...

  • Ruby之单引号和双引号定义字符串

    在Ruby中 ' '和" "都可以定义字符串例如'string' "string"这两种方式定义字符串的区别...

  • Ruby字符串处理

    ruby字符串处理方法 截取 单个字符 子串 替换 替换单个 替换子集 包含

  • Ruby字符串编码

    每一个字符串都有一个 Encoding 对象,也就是说在创建字符串的时候就要为它指定一个 Encoding 对象。...

  • Ruby字符串类

    字符串的创建 1.通常的创建方式 2.使用%Q,%q当创建包含",'的字符串时候,比起",'进行转义,使用%Q或者...

网友评论

      本文标题:Ruby字符串

      本文链接:https://www.haomeiwen.com/subject/lorcpttx.html