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>
#include<cstring>
using namespace std; 
  
char *removeSpaces(char *str) 
{ 
    int i,j;
    for(i=0;str[i]==' ';i++);
    if(i)
     for(j=0;str[j]=str[i+j];j++);
   for(i=strlen(str)-1;str[i]==' ';i--);
   str[i+1]='\0';
   return str;
} 
  

int main() 
{ 
    char str[20];
    cin.getline(str,20);
    cout<<removeSpaces(str);
    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.

 

Input:

  Code Speedy

Output:

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