如果字符串长度超过90个字符,如何将字符串分成2部分



我有一个动态字符串(在Ruby程序中),我需要分割它,如果它长于91个字符。我需要把它分成几个部分,在关闭逗号',' char。

字符串的例子:

"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41"

谢谢!

这就是你需要的:

string.split(',').in_groups_of(90, false)
结果:

> str.split(',').in_groups_of(10, false)
=> [["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
 ["11", "12", "13", "14", "15", "16", "17", "18", "19", "20"],
 ["21", "22", "23", "24", "25", "26", "27", "28", "29", "30"],
 ["31", "32", "33", "34", "35", "36", "37", "38", "39", "40"],
 ["41"]]

str.split(',').in_groups_of(10, false).map {|s| s.join(',')}
结果:

> str.split(',').in_groups_of(10, false).map {|s| s.join(',')}
=> ["1,2,3,4,5,6,7,8,9,10",
 "11,12,13,14,15,16,17,18,19,20",
 "21,22,23,24,25,26,27,28,29,30",
 "31,32,33,34,35,36,37,38,39,40",
 "41"]

更新:

使用普通Ruby(非Rails):

str.split(',').each_slice(10).to_a

或加入:

str.split(',').each_slice(10).map {|s| s.join(',')}

try this

  str.split(',') if str.length>91

我假设您需要一个字符串并返回一个数组,其中数组的每个元素是长度为91或更少的字符串。但是您希望生成的字符串在使用分隔符分隔之前尽可能长。

a = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41"
def my_split(str, delimiter, max_length)
    return [str] if str.length <= max_length
    i = str.rindex(delimiter, max_length)
    the_rest = my_split(str[i+1..-1], delimiter, max_length)
    return [str[0..i-1]] + the_rest
end
for r in my_split(a, ',', 90)
    puts "#{r}:Length: #{r.length.to_s}"
end

结果:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33:Length: 89
34,35,36,37,38,39,40,41:Length: 23

最新更新