简体   繁体   中英

How do I add characters between each character in a string in ruby?

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"

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.

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('--')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM