如何在一定位置后将字符串拆分为2个部分

时间:2022-08-22 11:54:23

For example I have some random string:

例如,我有一些随机字符串:

str = "26723462345"

And I want to split it in 2 parts after 6-th char. How to do this correctly?

我希望在第6个字符之后将它分成两部分。如何正确地做到这一点?

Thank you!

谢谢!

6 个解决方案

#1


24  

This should do it

这应该做到这一点

[str[0..5], str[6..-1]]

or

要么

 [str.slice(0..5), str.slice(6..-1)]

Really should check out http://corelib.rubyonrails.org/classes/String.html

真的应该查看http://corelib.rubyonrails.org/classes/String.html

#2


10  

part1, part2 = str.slice!(0...6), str

puts part1  # => 267234
puts part2  # => 62345
puts str    # => 62345

#3


4  

The best way IMO is string.scan(/.{6}/)

IMO的最佳方式是s​​tring.scan(/。{6} /)

irb(main)> str
=> "abcdefghijklmnopqrstuvwxyz"
irb(main)> str.scan(/.{13}/)
=> ["abcdefghijklm", "nopqrstuvwxyz"]

#4


2  

_, part1, part2 = str.partition /.{6}/

https://ruby-doc.org/core-1.9.3/String.html#method-i-partition

https://ruby-doc.org/core-1.9.3/String.html#method-i-partition

#5


1  

As a fun answer, how about:

作为一个有趣的答案,如何:

str.split(/(^.{1,6})/)[1..-1]

This works because split returns the capture group matches, in addition to the parts of the string before and after the regular expression.

这是有效的,因为除了正则表达式之前和之后的字符串部分之外,split还返回捕获组匹配。

#6


0  

Here's a reusable version for you:

这是适合您的可重用版本:

str       = "26723462345"
n         = str.length
boundary  = 6
head      = str.slice(0, boundary) # => "267234" 
tail      = str.slice(boundary, n) # => "62345" 

It also preserves the original string, which may come in handy later in the program.

它还保留了原始字符串,这可能会在程序后期派上用场。

#1


24  

This should do it

这应该做到这一点

[str[0..5], str[6..-1]]

or

要么

 [str.slice(0..5), str.slice(6..-1)]

Really should check out http://corelib.rubyonrails.org/classes/String.html

真的应该查看http://corelib.rubyonrails.org/classes/String.html

#2


10  

part1, part2 = str.slice!(0...6), str

puts part1  # => 267234
puts part2  # => 62345
puts str    # => 62345

#3


4  

The best way IMO is string.scan(/.{6}/)

IMO的最佳方式是s​​tring.scan(/。{6} /)

irb(main)> str
=> "abcdefghijklmnopqrstuvwxyz"
irb(main)> str.scan(/.{13}/)
=> ["abcdefghijklm", "nopqrstuvwxyz"]

#4


2  

_, part1, part2 = str.partition /.{6}/

https://ruby-doc.org/core-1.9.3/String.html#method-i-partition

https://ruby-doc.org/core-1.9.3/String.html#method-i-partition

#5


1  

As a fun answer, how about:

作为一个有趣的答案,如何:

str.split(/(^.{1,6})/)[1..-1]

This works because split returns the capture group matches, in addition to the parts of the string before and after the regular expression.

这是有效的,因为除了正则表达式之前和之后的字符串部分之外,split还返回捕获组匹配。

#6


0  

Here's a reusable version for you:

这是适合您的可重用版本:

str       = "26723462345"
n         = str.length
boundary  = 6
head      = str.slice(0, boundary) # => "267234" 
tail      = str.slice(boundary, n) # => "62345" 

It also preserves the original string, which may come in handy later in the program.

它还保留了原始字符串,这可能会在程序后期派上用场。