Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string into 2 parts after certain position

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?

Thank you!

like image 463
thesis Avatar asked Oct 06 '11 09:10

thesis


People also ask

How do you split a string after a character?

To cut a string after a specific character, you can use the substring() method, slice() method, or split() method. The slice() and the substring() methods work the same as they extract the string by cutting other parts based on the specific character.

How do I split a string into two parts in SQL?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument. FROM STRING_SPLIT( 'An example sentence.


2 Answers

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

like image 147
Yule Avatar answered Sep 18 '22 05:09

Yule


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"]
like image 30
Jordan Running Avatar answered Sep 18 '22 05:09

Jordan Running