Easiest and most efficient don't usually go together…

Here's a possible solution for in-place removal:

void remove_spaces(char* s) {
    char* d = s;
    do {
        while (*d == ' ') {
            ++d;
        }
    } while (*s++ = *d++);
}
Answer from Aaron on Stack Overflow
🌐
PREP INSTA
prepinsta.com › home › c program › c program to remove spaces from a string
C Program to Remove Spaces from a String
October 13, 2022 - If the current character is not ... } // Driver program to test above function int main() { char str[] = "P re p i n sta "; removeSpaces(str); printf("%s", str); return 0; } ... /*Use this code no need to write too many line ...
Top answer
1 of 16
112

Easiest and most efficient don't usually go together…

Here's a possible solution for in-place removal:

void remove_spaces(char* s) {
    char* d = s;
    do {
        while (*d == ' ') {
            ++d;
        }
    } while (*s++ = *d++);
}
2 of 16
23

As we can see from the answers posted, this is surprisingly not a trivial task. When faced with a task like this, it would seem that many programmers choose to throw common sense out the window, in order to produce the most obscure snippet they possibly can come up with.

Things to consider:

  • You will want to make a copy of the string, with spaces removed. Modifying the passed string is bad practice, it may be a string literal. Also, there are sometimes benefits of treating strings as immutable objects.
  • You cannot assume that the source string is not empty. It may contain nothing but a single null termination character.
  • The destination buffer can contain any uninitialized garbage when the function is called. Checking it for null termination doesn't make any sense.
  • Source code documentation should state that the destination buffer needs to be large enough to contain the trimmed string. Easiest way to do so is to make it as large as the untrimmed string.
  • The destination buffer needs to hold a null terminated string with no spaces when the function is done.
  • Consider if you wish to remove all white space characters or just spaces ' '.
  • C programming isn't a competition over who can squeeze in as many operators on a single line as possible. It is rather the opposite, a good C program contains readable code (always the single-most important quality) without sacrificing program efficiency (somewhat important).
  • For this reason, you get no bonus points for hiding the insertion of null termination of the destination string, by letting it be part of the copying code. Instead, make the null termination insertion explicit, to show that you haven't just managed to get it right by accident.

What I would do:

void remove_spaces (char* restrict str_trimmed, const char* restrict str_untrimmed)
{
  while (*str_untrimmed != '\0')
  {
    if(!isspace(*str_untrimmed))
    {
      *str_trimmed = *str_untrimmed;
      str_trimmed++;
    }
    str_untrimmed++;
  }
  *str_trimmed = '\0';
}

In this code, the source string "str_untrimmed" is left untouched, which is guaranteed by using proper const correctness. It does not crash if the source string contains nothing but a null termination. It always null terminates the destination string.

Memory allocation is left to the caller. The algorithm should only focus on doing its intended work. It removes all white spaces.

There are no subtle tricks in the code. It does not try to squeeze in as many operators as possible on a single line. It will make a very poor candidate for the IOCCC. Yet it will yield pretty much the same machine code as the more obscure one-liner versions.

When copying something, you can however optimize a bit by declaring both pointers as restrict, which is a contract between the programmer and the compiler, where the programmer guarantees that the destination and source are not the same address. This allows more efficient optimization, since the compiler can then copy straight from source to destination without temporary memory in between.

🌐
w3resource
w3resource.com › python-exercises › re › python-re-exercise-39.php
Python: Remove multiple spaces in a string
July 22, 2025 - import re text1 = 'Python Exercises' print("Original string:",text1) print("Without extra spaces:",re.sub(' +',' ',text1)) ... Write a Python program to collapse multiple consecutive spaces in a string into a single space.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › remove-spaces-from-a-given-string
Remove spaces from a given string - GeeksforGeeks
April 11, 2026 - Traverse the string and whenever a space is found, shift all the following characters one position to the left and reduce the effective length of the string. ... Initialize n = 5 (length of the string).
🌐
W3Schools
w3schools.in › c-programming › examples › c-program-to-remove-extra-spaces-from-given-string
C Program to Remove Extra Spaces from Given String
*/ while (inputs[c] != '\0') { if (!(inputs[c] == ' ' && inputs[c + 1] == ' ')) { output[d] = inputs[c]; d++; } c++; } output[d] = '\0'; printf("Text after removing extra spaces:\n%s\n", output); }
🌐
w3resource
w3resource.com › python-exercises › string › python-data-type-string-exercise-57.php
Python: Remove spaces from a given string - w3resource
June 12, 2025 - # Call the 'remove_spaces' function with different input strings and print the results. print(remove_spaces("w 3 res ou r ce")) print(remove_spaces("a b c")) ... Write a Python program to remove all spaces from a string using the replace() method.
🌐
Codeforwin
codeforwin.org › home › c program to remove spaces, blanks from a string
C program to remove spaces, blanks from a string - Codeforwin
July 20, 2025 - Declare another string newString with same size as of str, to store string without blanks. For each character in str copy to newString. If current character in str is white space.
🌐
Techie Delight
techiedelight.com › home › string › remove all extra spaces from a string
Remove all extra spaces from a string | Techie Delight
September 18, 2025 - Hello. This is a C++ program!! The time complexity of the above solution is O(n), where n is the length of the input string and doesn’t require any extra space for the conversion.
Find elsewhere
🌐
Programiz
programiz.com › java-programming › examples › remove-whitespaces
Java Program to Remove All Whitespaces from a String
import java.util.Scanner; class Main { public static void main(String[] args) { // create an object of Scanner Scanner sc = new Scanner(System.in); System.out.println("Enter the string"); // take the input String input = sc.nextLine(); System.out.println("Original String: " + input); // remove white spaces input = input.replaceAll("\\s", ""); System.out.println("Final String: " + input); sc.close(); } }
🌐
Scaler
scaler.com › home › topics › program to remove all the white spaces from a string in c
Program to Remove All the White Spaces from a String in C - Scaler Topics
October 28, 2022 - Let's first create a trim() method that trims the left space and the right space of the given string using the ltrim(), and the rtrim() method then after the function remove_space is used to trim the remaining spaces in the given string.
🌐
TutorialsPoint
tutorialspoint.com › c-program-to-remove-extra-spaces-using-string-concepts
C program to remove extra spaces using string concepts.
len = strlen(string); for(i=0; i<len; i++){ if(string[0]==' '){ for(i=0; i<(len-1); i++) string[i] = string[i+1]; string[i] = '\0'; len--; i = -1; continue; } if(string[i]==' ' && string[i+1]==' '){ for(j=i; j<(len-1); j++){ string[j] = string[j+1]; } string[j] = '\0'; len--; i--; } } Following ...
🌐
Medium
rameshfadatare.medium.com › java-program-to-remove-all-whitespace-from-a-string-819ccfb84997
Java Program to Remove All Whitespace from a String | by Ramesh Fadatare | Medium
December 13, 2024 - // Java Program to Remove All Whitespace from a String import java.util.Scanner; public class RemoveWhitespace { public static void main(String[] args) { // Step 1: Read the string from the user try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter a string: "); String input = scanner.nextLine(); // Step 2: Remove all whitespace characters String noWhitespaceString = input.replaceAll("\\s", ""); // Step 3: Display the result System.out.println("String without whitespace: " + noWhitespaceString); } } }
🌐
Finxter
blog.finxter.com › home › learn python blog › a simple guide to remove multiple spaces in a string
A Simple Guide To Remove Multiple Spaces In A String - Be on the Right Side of Change
February 5, 2022 - We will keep checking it till the string has no multiple spaces. Finally, we will return the string. Here’s a complete guide for you to learn about Python’s string replace method: Python String Replace · Now, let us have a look at the following code to understand how we can use the concept mentioned above to solve our problem. # Given string s = "Hello and Welcome to Finxter!" print("String with multiple spaces:") print(s) # Removing the multiple spaces using while loop if ' ' in s: while ' ' in s: s = s.replace(' ', ' ') print("String after removing multiple spaces:") print(s)
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-remove-spaces-from-a-string
Remove spaces from a string in Python - GeeksforGeeks
If we only want to remove spaces from the beginning of the string, we can use lstrip().
Published   July 11, 2025
🌐
W3Schools
w3schools.in › c-programming › examples › remove-spaces-from-string
C Program to Remove Spaces From String - W3schools
Input String: Prompt the user to enter a string. Use the gets() or fgets() function to take input. Remove Spaces: Iterate through each character of the string.
Top answer
1 of 3
4

It seems to be a common newbie confusion. Printing gets confused with other concepts. If a function prints something, then the function is 'returning' what is printed. This is completely untrue, printing is printing, nothing else.

If you want to write a function that removes spaces from a string, then that is what the function must do. Somehow a new string without the spaces must be created. How that function returns the modified string is a side issue.

Here's a function that removes spaces from a string.

void RemoveSpaces ( string &userString )
{
   string temp;
   for (size_t i = 0 ; i < userString.size() ; i ++ )
   {
      if (userString.at(i) != ' ' )
          temp.push_back(userString.at(i));
   }
   userString = temp;
}

This function works by looking for the non-spaces in userString and adding them to a new string temp. This is the string without spaces. Then at the end of the function it assigns this string back to userString. Because userString has been passed by reference this assignment modifies userInputString in main. That's the meaning of pass by reference. Changes to userString actually change the string that is being referred to.

It is possible to write a function that modifies userString directly, but that is more complicated code, so I chose to do it this way with a second string temp.

2 of 3
2

in the function RemoveSpaces, you are printing the srting without spaces but not updating it. So for example the string is "This is an example" it would just print "Thisisanexample" but the value of the string still remains the same. You will have to update the value of string in the function inorder to update the original string value, pass by reference doesn't automatically do it.

void RemoveSpaces ( string &userString )
{
   unsigned int i ; 
   int count = 0;
   for ( i = 0 ; i < userString.size() ; i ++ )
   {
      if ( userString.at(i) != ' ' )
      {
          userString.at(count++) = userString.at(i);
          cout << userString.at(i) ;
      }
   }
   userString.resize(count);
}

resize(count) is added cause for example orginial string - "This is an example" size - 18 updated string - "Thisisanexampleple" size - 18 This happens because updated string has a size of 15("Thisisanexample") but original has size of 18 so it will take 18-15 = 3 characters from original string and keep it in updated string. hence you need to resize the updated string to 15 i.e. the count variable which tracks size of updated string.

🌐
Javatpoint
javatpoint.com › program-to-remove-all-the-white-spaces-from-a-string
Program to remove all the white spaces from a string - Javatpoint
String: Once in a blue moon String after replacing space with &#39;-&#39;: Once-in-a-blue-moon One of the approach to accomplish this is by iterating through the string to find spaces. If... ... Program to find the frequency of odd &amp; even numbers in the given Matrix Explanation In this program, we need to find the frequencies of odd and even numbers present in the matrix.
🌐
Talent Battle
talentbattle.in › important-coding-questions-for-placement › write-a-program-to-remove-spaces-from-a-string
Program to Remove spaces from a string | Talent Battle
April 26, 2023 - Get a string as input and then remove all the spaces present in the string. ... If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023 · Ask Us Anything! Program to identify if the character is an alphabet or not ... Program to change the given matrix to transpose of the matrix.