Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove repeated spaces in a string?

Tags:

ruby

I have a string:

"foo (2 spaces) bar (3 spaces) baaar (6 spaces) fooo"

How do I remove repetitious spaces in it so there should be no more than one space between any two words?

like image 488
Kir Avatar asked Feb 05 '11 13:02

Kir


People also ask

How do I remove multiple spaces from a string?

You can also use the string split() and join() functions to remove multiple spaces from a string.

How do you delete multiple spaces with a single space in a string?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do you remove multiple spacing between words in Python?

Using re. sub() or split() + join() method to remove extra spaces between words in Python.


1 Answers

String#squeeze has an optional parameter to specify characters to squeeze.

irb> "asd  asd asd   asd".squeeze(" ") => "asd asd asd asd" 

Warning: calling it without a parameter will 'squezze' ALL repeated characters, not only spaces:

irb> 'aaa     bbbb     cccc 0000123'.squeeze => "a b c 0123" 
like image 125
Nakilon Avatar answered Sep 28 '22 01:09

Nakilon