How to Remove Repeated Spaces in a String

Is there a simple way to remove multiple spaces in a string?

>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'

How to remove repeated spaces from a string

Function based on the simplest state machine (DFA). Minimum of memory reallocations.

State is number of continuous spaces.

J is count of deleted spaces.

  function DeleteRepeatedSpaces(const s: string): string;
var
i, j, State: Integer;
begin
SetLength(Result, Length(s));
j := 0;
State := 0;

for i := 1 to Length(s) do begin

if s[i] = ' ' then
Inc(State)
else
State := 0;

if State < 2 then
Result[i - j] := s[i]
else
Inc(j);

end;

if j > 0 then
SetLength(Result, Length(s) - j);
end;

How do I replace multiple spaces with a single space in C#?

string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");

How to remove duplicate white spaces in a string?

try

"abc                  def. fds                            sdff."
.replace(/\s+/g,' ')

or

"abc                  def. fds                            sdff."
.split(/\s+/)
.join(' ');

or use this allTrim String extension

String.prototype.allTrim = String.prototype.allTrim ||
function(){
return this.replace(/\s+/g,' ')
.replace(/^\s+|\s+$/,'');
};
//usage:
alert(' too much whitespace here right? '.allTrim());
//=> "too much whitespace here right?"

How do I remove repeated spaces in a string?

>> str = "foo  bar   bar      baaar"
=> "foo bar bar baaar"
>> str.split.join(" ")
=> "foo bar bar baaar"
>>

How to remove multiple spaces in Strings with Swift 2

In Swift 2, join has become joinWithSeparator and you call it on the array.

In filter, isEmpty should be called on the current iteration item $0.

To replace whitespaces and newline characters with unique space characters as in your question:

extension String {
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}

let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"

Because your function does not take any parameter you could make it a property instead:

extension String {
var condensedWhitespace: String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}

let result = "Hello World.\nHello!".condensedWhitespace // "Hello World. Hello!"

In Swift 3 there's even more changes.

Function:

extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}

let result = "Hello World.\nHello!".condenseWhitespace()

Property:

extension String {
var condensedWhitespace: String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}

let result = "Hello World.\nHello!".condensedWhitespace

In Swift 4.2 NSCharacterSet is now CharacterSet, and you can omit and use dot syntax:

extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}

let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"

Regex to replace multiple spaces with a single space

Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':

string = string.replace(/\s\s+/g, ' ');

If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

string = string.replace(/  +/g, ' ');

Merge Multiple spaces to single space; remove trailing/leading spaces

This seems to meet your needs.

string <- "  Hi buddy   what's up   Bro "
library(stringr)
str_replace(gsub("\\s+", " ", str_trim(string)), "B", "b")
# [1] "Hi buddy what's up bro"


Related Topics



Leave a reply



Submit