Remove extra spaces from a string
Last Updated :
03 Dec, 2023
Given a string containing many consecutive spaces, trim all spaces so that all words should contain only a single space between them. The conversion should be done in-place and solution should handle trailing and leading spaces and also remove preceding spaces before common punctuation like full stop, comma and a question mark.
Examples:
Input:
str = " Hello Geeks . Welcome to GeeksforGeeks . ";
Output:
"Hello Geeks. Welcome to GeeksforGeeks."
Input:
str = "GeeksforGeeks";
Output:
"GeeksforGeeks"
(No change is needed)
This problem is an extension of Remove spaces from a given string
Method 1:
- The idea is to maintain 2 pointers. Initially both point to the beginning of the array.
- The first pointer keeps track of next position to be filled in output string.
- The second pointer is advanced to read all characters of the string one by one.
- On finding any non-space character, the character is copied to the location of the first pointer and then both the first and second pointers are advanced.
- If non-space character is a full stop, comma or a question mark, we also remove any preceding space before it.
- On finding consecutive space characters, one only space is copied to the location of the first pointer and rest are ignored. The leading and trailing spaces are handled separately in the solution.
Below is C++ implementation of above idea.
C++
#include <iostream>
using namespace std;
void removeSpaces(string &str)
{
int n = str.length();
int i = 0, j = -1;
bool spaceFound = false ;
while (++j < n && str[j] == ' ' );
while (j < n)
{
if (str[j] != ' ' )
{
if ((str[j] == '.' || str[j] == ',' ||
str[j] == '?' ) && i - 1 >= 0 &&
str[i - 1] == ' ' )
str[i - 1] = str[j++];
else
str[i++] = str[j++];
spaceFound = false ;
}
else if (str[j++] == ' ' )
{
if (!spaceFound)
{
str[i++] = ' ' ;
spaceFound = true ;
}
}
}
if (i <= 1)
str.erase(str.begin() + i, str.end());
else
str.erase(str.begin() + i - 1, str.end());
}
int main()
{
string str = " Hello Geeks . Welcome to"
" GeeksforGeeks . " ;
removeSpaces(str);
cout << str;
return 0;
}
|
Java
class Main{
public static String removeSpaces(String s) {
int n = s.length();
int i = 0 , j = - 1 ;
boolean spaceFound = false ;
while (j < n - 1 && s.charAt(j + 1 ) == ' ' ) {
j++;
}
while (j < n) {
if (s.charAt(j) != ' ' ) {
if ((s.charAt(j) == '.' || s.charAt(j) == ',' ||
s.charAt(j) == '?' ) && i - 1 >= 0 &&
s.charAt(i - 1 ) == ' ' ) {
s = s.substring( 0 , i - 1 ) + s.charAt(j) + s.substring(i);
j++;
} else {
s = s.substring( 0 , i) + s.charAt(j) + s.substring(i + 1 );
i++;
j++;
}
spaceFound = false ;
} else if (s.charAt(j) == ' ' ) {
if (!spaceFound) {
s = s.substring( 0 , i) + ' ' + s.substring(i + 1 );
i++;
spaceFound = true ;
}
j++;
}
}
if (i <= 1 ) {
s = s.substring( 0 , i);
} else {
s = s.substring( 0 , i - 1 );
}
return s;
}
public static void main(String[] args) {
String str = " Hello Geeks . Welcome to"
+ " GeeksforGeeks . " ;
str = removeSpaces(str);
System.out.println(str);
}
}
|
Python3
def removeSpaces(s):
n = len (s)
i = 0
j = - 1
spaceFound = False
while j < n - 1 and s[j + 1 ] = = ' ' :
j + = 1
while j < n:
if s[j] ! = ' ' :
if ((s[j] = = '.' or s[j] = = ',' or
s[j] = = '?' ) and i - 1 > = 0 and
s[i - 1 ] = = ' ' ):
s = s[:i - 1 ] + s[j] + s[i:]
j + = 1
else :
s = s[:i] + s[j] + s[i + 1 :]
i + = 1
j + = 1
spaceFound = False
elif s[j] = = ' ' :
if not spaceFound:
s = s[:i] + ' ' + s[i + 1 :]
i + = 1
spaceFound = True
j + = 1
if i < = 1 :
s = s[:i]
else :
s = s[:i - 1 ]
return s
str = " Hello Geeks . Welcome to" \
" GeeksforGeeks . "
str = removeSpaces( str )
print ( str )
|
C#
using System;
public class Gfg
{
public static void Main()
{
string str = " Hello Geeks . Welcome to" +
" GeeksforGeeks . " ;
removeSpaces( ref str);
Console.WriteLine(str);
}
public static void removeSpaces( ref string str)
{
int n = str.Length;
int i = 0, j = -1;
bool spaceFound = false ;
while (++j < n && str[j] == ' ' );
while (j < n)
{
if (str[j] != ' ' )
{
if ((str[j] == '.' || str[j] == ',' ||
str[j] == '?' ) && i - 1 >= 0 &&
str[i - 1] == ' ' )
str = str.Remove(i - 1, 1).Insert(i - 1, str[j++].ToString());
else
{
str = str.Remove(i, 1).Insert(i, str[j++].ToString());
i++;
}
spaceFound = false ;
}
else if (str[j++] == ' ' )
{
if (!spaceFound)
{
str = str.Remove(i, 0).Insert(i, " " );
i++;
spaceFound = true ;
}
}
}
if (i <= 1)
str = str.Remove(i, n - i);
else
str = str.Remove(i - 1, n - i + 1);
}
}
|
Javascript
function removeSpaces(str) {
let n = str.length;
let i = 0, j = -1;
let spaceFound = false ;
while (++j < n && str[j] == ' ' );
while (j < n) {
if (str[j] != ' ' ) {
if ((str[j] == '.' || str[j] == ',' ||
str[j] == '?' ) && i - 1 >= 0 &&
str[i - 1] == ' ' )
str = str.substr(0, i - 1) + str[j++] + str.substr(i);
else
str = str.substr(0, i++) + str[j++] + str.substr(i);
spaceFound = false ;
}
else if (str[j++] == ' ' ) {
if (!spaceFound) {
str = str.substr(0, i++) + ' ' + str.substr(i);
spaceFound = true ;
}
}
}
if (i <= 1)
str = str.substr(0, i);
else
str = str.substr(0, i - 1);
return str;
}
let str = " Hello Geeks . Welcome to"
+ " GeeksforGeeks . " ;
str = removeSpaces(str);
console.log(str);
|
Output:
Hello Geeks. Welcome to GeeksforGeeks.
Time complexity of above solution is O(n).
Auxiliary Space is O(1) as the conversion is done in-place.
Method 2:
Another solution using predefined functions in Python 3:
C++
#include <iostream>
#include <string>
int main() {
std::string input_string = " Hello Geeks . Welcome , Do you love Geeks , Geeks ? " ;
std::string output_string;
bool space_flag = false ;
for ( size_t index = 0; index < input_string.length(); ++index) {
if (input_string[index] != ' ' ) {
if (space_flag) {
if (input_string[index] == '.' || input_string[index] == '?' || input_string[index] == ',' ) {
} else {
output_string += ' ' ;
}
space_flag = false ;
}
output_string += input_string[index];
} else if (index > 0 && input_string[index - 1] != ' ' ) {
space_flag = true ;
}
}
std::cout << output_string << std::endl;
return 0;
}
|
Java
public class Main {
public static void main(String[] args) {
String inputString = " Hello Geeks . Welcome , Do you love Geeks , Geeks ? " ;
String outputString = "" ;
boolean spaceFlag = false ;
for ( int index = 0 ; index < inputString.length(); ++index) {
if (inputString.charAt(index) != ' ' ) {
if (spaceFlag) {
if (inputString.charAt(index) == '.' || inputString.charAt(index) == '?' || inputString.charAt(index) == ',' ) {
} else {
outputString += ' ' ;
}
spaceFlag = false ;
}
outputString += inputString.charAt(index);
} else if (index > 0 && inputString.charAt(index - 1 ) != ' ' ) {
spaceFlag = true ;
}
}
System.out.println(outputString);
}
}
|
Python3
input_string = \
' Hello Geeks . Welcome , Do you love Geeks , Geeks ? '
output_string = []
space_flag = False
for index in range ( len (input_string)):
if input_string[index] ! = ' ' :
if space_flag = = True :
if (input_string[index] = = '.'
or input_string[index] = = '?'
or input_string[index] = = ',' ):
pass
else :
output_string.append( ' ' )
space_flag = False
output_string.append(input_string[index])
elif input_string[index - 1 ] ! = ' ' :
space_flag = True
print (''.join(output_string))
|
C#
using System;
class Program
{
static void Main()
{
string inputString = " Hello Geeks . Welcome to GeeksforGeeks , Do you love Geeks , Geeks ? " ;
char [] outputArray = new char [inputString.Length];
int outputIndex = 0;
bool spaceFlag = false ;
for ( int index = 0; index < inputString.Length; ++index)
{
if (inputString[index] != ' ' )
{
if (spaceFlag)
{
if (inputString[index] == '.' || inputString[index] == '?' || inputString[index] == ',' )
{
}
else
{
outputArray[outputIndex++] = ' ' ;
}
spaceFlag = false ;
}
outputArray[outputIndex++] = inputString[index];
}
else if (index > 0 && inputString[index - 1] != ' ' )
{
spaceFlag = true ;
}
}
string outputString = new string (outputArray, 0, outputIndex);
Console.WriteLine(outputString);
}
}
|
Javascript
let inputString = " Hello Geeks . Welcome , Do you love Geeks , Geeks ? " ;
let outputString = "" ;
let spaceFlag = false ;
for (let index = 0; index < inputString.length; ++index) {
if (inputString[index] !== ' ' ) {
if (spaceFlag) {
if (inputString[index] === '.' || inputString[index] === '?' || inputString[index] === ',' ) {
} else {
outputString += ' ' ;
}
spaceFlag = false ;
}
outputString += inputString[index];
} else if (index > 0 && inputString[index - 1] !== ' ' ) {
spaceFlag = true ;
}
}
console.log(outputString);
|
Output:
Hello Geeks. Welcome to GeeksforGeeks. Do you love Geeks, Geeks?
Time complexity of above solution is O(n).
Auxiliary Space is O(n) as another list had to be created.
Method 3: (Using built-in function)
C++
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string str = " Hello Geeks . Welcome , Do you love Geeks , Geeks ? " ;
std::regex pattern( "\\s+" );
std::string result = std::regex_replace(str, pattern, " " );
size_t firstNonSpace = result.find_first_not_of( " " );
size_t lastNonSpace = result.find_last_not_of( " " );
if (firstNonSpace != std::string::npos && lastNonSpace != std::string::npos) {
result = result.substr(firstNonSpace, lastNonSpace - firstNonSpace + 1);
}
std::cout << result << std::endl;
return 0;
}
|
Java
public class GFG {
public static void main(String args[]) {
String str = " Hello Geeks . Welcome , Do you love Geeks , Geeks ? " ;
System.out.println(str.replaceAll( "\\s+" , " " ).trim());
}
}
|
Python3
str = " Hello Geeks . Welcome , Do you love Geeks , Geeks ? "
import re
str = re.sub( '\s+' , ' ' , str ).strip()
print ( str )
|
C#
using System;
class Program {
static void Main( string [] args)
{
string str
= " Hello Geeks . Welcome , Do you love Geeks , Geeks ? " ;
Console.WriteLine(
System.Text.RegularExpressions.Regex.Replace(
str.Trim(), @"\s+" , " " ));
}
}
|
Javascript
<script>
var str = " Hello Geeks . Welcome , Do you love Geeks , Geeks ? " ;
document.write(str.replace( "\\s+" , " " ).trim());
</script>
|
Output:
Hello Geeks . Welcome , Do you love Geeks , Geeks ?
Time Complexity: O(n), where n is the number of characters in the string.
Auxiliary Space: O(1), as there are only lowercase letters.
This article is contributed by Aarti_Rathi and Aditya Goel.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...