0

If I have a string "hello", how would I add characters between each character in the string so it would look like "h--e--l--l--o"

3
  • @Sebastian, I do not doubt that this question is a dup but it not a dup of the question you referenced in closing the question. The earlier question would ask how 'hello' could be converted to 'h-e-l-l-o-', not to 'h-e-l-l-o', a signficant different. I suggest it be reopened until a suitable dup reference is found. Commented Apr 12, 2021 at 18:00
  • Yess, I know there was a pretty similar question. If found we can update this and/or reopen it. Thanks @CarySwoveland. Commented Apr 12, 2021 at 18:11
  • @Sebastian, I voted to reopen and, voilà, it reopened. I thought several votes were need for that to happen (unless you reopened it). Reclose if you wish. Confused in Victoria. Commented Apr 12, 2021 at 18:33

2 Answers 2

3

You can do that without converting the string to an array by using String#gsub with a regular expression:

"hello".gsub(/(?<=.)(?=.)/, '--')
  #=> "h--e--l--l--o".

(?<=.) is a positive lookbehind, asserting that the match is preceded by a character and (?=.) is a positive lookahead, asserting that the match is followed by a character. Note that matches are zero-width; it is the locations between consecutive characters that are matched.

Sign up to request clarification or add additional context in comments.

Comments

2

There are many solutions to this, I would suggest the following :

1/ split the string into an array of individual characters with chars

"hello".chars
=> ["h", "e", "l", "l", "o"]

2/ join them with the two characters you want to add in-between each character

["h", "e", "l", "l", "o"].join('--')
=> "h--e--l--l--o"

You can execute this in one line as such :

"hello".chars.join('--')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.