📜  Ruby – String split() 方法和示例

📅  最后修改于: 2022-05-13 01:54:49.793000             🧑  作者: Mango

Ruby – String split() 方法和示例

split是 Ruby 中的 String 类方法,用于根据指定的模式将给定的字符串拆分为子字符串数组。

这里的模式可以是正则表达式或字符串。如果 pattern 是正则表达式或字符串,则 str 在模式匹配的地方被分割。

示例 1:

arr = str.split(pattern, limit) public

输出:

# Ruby program to demonstrate split method
   
# Split without parameters
# Here the pattern is a 
# single whitespace
myArray = "Geeks For Geeks".split
puts myArray

示例 2:

Geeks
For
Geeks

输出:

# Ruby program to demonstrate split method
  
# Here pattern is a regular expression
# limit value is 2
# / / is one white space
myArray = "Geeks For Geeks".split(/ /, 2)
puts myArray

示例 3:

Geeks
For Geeks

输出:

# Ruby program to demonstrate split method
  
# Here the pattern is a regular expression
# limit value is -1
# if the limit is negative there is no 
# limit to the number of fields returned,
# and trailing null fields are not 
# suppressed.
myArray = "geeks geeks".split('s', -1)
puts myArray