Removing leading and trailing spaces from a string in C++

This tutorial is focused on the strings, removing all the spaces before the string or leading to the string and the spaces after the string or trailing to the string which is entered by the user using C++

Algorithm for creating the program

  • We will create a function to remove spaces as required
  • First, we count the leading spaces
  • Then we will shift each character of the string and overwrite all the leading spaces
  • Now, we will count the trailing spaces
  • Then we will remove them by changing the length of the string

C++ Program for removing leading and trailing spaces from a string

#include <iostream>
using namespace std; 
char *removeSpaces(char *str) 
    int i,j;
    for(i=0;str[i]==' ';i++);
   for(i=strlen(str)-1;str[i]==' ';i--);
   return str;

int main() 
    char str[20];
    return 0;

Explanation of Function

  • Number of leading spaces are counted by the for loop
  • Now, it is checked if  i= 0 then there is no space leading. Thus, shifting will not be performed
  • The shifting is performed to remove the leading spaces by using for loop
  • The string is traversed from reverse and the null character is placed before the first character found as traversing from right

Note: All for loops should be terminated as they do not include any statement under them.



  Code Speedy


Code Speedy

The output above has no spaces before and after the string but there is space between the string. Thus, only the leading and trailing spaces are removed successfully using the above C++ program.

Recommended tutorials:

Leave a Reply

Your email address will not be published. Required fields are marked *