How to split string into 2 parts after certain position

后端 未结 6 1564
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 10:53

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条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 11:20

    Here’s on option. Be aware, however, that it will mutate your original string:

    part1, part2 = str.slice!(0...6), str
    
    p part1  # => "267234"
    p part2  # => "62345"
    p str    # => "62345"
    

    Update

    In the years since I wrote this answer I’ve come to agree with the commenters complaining that it might be excessively clever. Below are a few other options that don’t mutate the original string.

    Caveat: This one will only work with ASCII characters.

    str.unpack("a6a*")
    # => ["267234", "62345"]
    

    The next one uses the magic variable $', which returns the part of the string after the most recent Regexp match:

    part1, part2 = str[/.{6}/], $'
    p [part1, part2]
    # => ["267234", "62345"]
    

    And this last one uses a lookbehind to split the string in the right place without returning any extra parts:

    p str.split(/(?<=^.{6})/)
    # => ["267234", "62345"]
    

提交回复
热议问题