Remove leading spaces from a string in C++

To remove leading spaces from a string in C++, you can create a function that iterates through the string and finds the position of the first non-space character, then returns the substring starting from that position Here’s step by step guide  how you can do this:

Remove Leading spaces
1. Include Necessary Headers:

          #include <iostream>
#include <string>

  • #include <iostream> is for standard input and output.
  • #include <string> is for the std::string class.

2.Replace Function:

      string removeLeadingSpaces(const string &str) {
size_t start = str.find_first_not_of(‘ ‘);
if (start == string::npos) {
return “”; // The string is composed entirely of spaces
}
return str.substr(start);
}

  • removeLeadingSpaces takes a constant reference to a string str.
  • str.find_first_not_of(' ') finds the position of the first character that is not a space. If no such character is found, it returns string::npos.
  • If the string is composed entirely of spaces, the function returns an empty string.
  • Otherwise, it returns a substring starting from the first non-space character.

complete code :

#include <iostream>
#include <string>

using namespace std;

string removeLeadingSpaces(const string &str) {
size_t start = str.find_first_not_of(‘ ‘);
if (start == string::npos) {
return “”; // The string is composed entirely of spaces
}
return str.substr(start);
}

int main() {
string str = ” Hello, world!”;

string result = removeLeadingSpaces(str);

cout << “Original string: ‘” << str << “‘” << endl;
cout << “Modified string: ‘” << result << “‘” << endl;

return 0;
}

 

output :

 

Original string: ‘            Hello,     world!’
Modified string: ‘Hello, world!’

Leave a Comment

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

Scroll to Top