ruby学习-字符串

时间:2024-06-20 13:04:08

字符串

1.创建字符1:new用来创建新字符,empty?检验字符是否为空

title = String.new #=> ""

title.empty? #=>true

创建字符2:用"="

str = "hello"或者str='hello'(ps:单/双 引号区别," "会转义,' '原样输出,"\n"是换行效果)

2.通用分隔符 %+例如!!,{},[]

str = %! hehe !

3.嵌入文档

sonnet =<<
this is a language i think good
do u know
30
puts sonnet

4.字符连接

+,<<,.contact方法(此只连一个字符串)

Object.freeze冻结字符串,禁止改变

5.字符串访问

e.g. str="a horse!"

str['hor']#若存在'hor则返回‘hor',否则返回nil表示搜索字符串不存在。

str[7]#=>33,因为是个"!",其字符编码是33,

所以str[7].chr #=>"!"

str[2,2]#=>"ho", str[2,2].capitalize#=>"Ho"

str[0..3]#=>a ho而 str[0...3]#=>a h  三个点表示不包括最后一个字符

6.字符串比较:

<=>比较的是字符编码,-1,0,1代表小于,等于,大于"a" <=>"a" #=>0

而casecmp则会忽略大小写"a"<=>"A" #=>1,"a".casecmp "A" #=>0

6.字符操作:

6.1字符插入:insert方法

"Be careful".insert 3,"very " #=>Be very careful

6.2字符替换

str="sun of bitch"

(1) str["bitch"]="brother" #=>sun of brother

(2) str[7]="a " #=>sun of a bitch

(3) str[3,11]="shine" #=>sunshine

(4)str[/bitch$/]="brother"  #正则表达式