Ruby中高效应用substring的方法
在Ruby中,可使用String#slice
还是String#[]
方法来获得字符串的子串。这两种方法可以传入起始索引和长度参数,也能够传入一个范围对象来指定子串的范围。
例如,可以这样获得从索引2开始的3个字符的子串:
str = "hello world"
sub_str = str.slice(2, 3)
puts sub_str # Output: "llo"
也能够使用范围对象来获得子串:
sub_str = str[2..4]
puts sub_str # Output: "llo"
另外,还可使用String#start_with?
和String#end_with?
方法来判断一个字符串是否是以指定的子串开头或结尾。这两个方法返回一个布尔值,用于判断结果。
str = "hello world"
puts str.start_with?("hello") # Output: true
puts str.end_with?("world") # Output: true
tiktok粉丝购买:https://www.smmfensi.com/
TOP