Parsing Data using std::string

Trimming Extra Spaces

What if a key in our config file has multiple spaces before or after it, such as " KEY : VALUE"? How can we trim leading/trailing spaces from the key and value?

Abstract art representing computer programming

If a key or value in our configuration file has extra spaces at the beginning (leading) or end (trailing), we need a way to remove them. This process is often called "trimming".

Implementing Trim()

We can create a helper function called Trim() that takes a std::string and returns a new std::string with the leading and trailing spaces removed.

#include <iostream>
#include <string>

std::string Trim(const std::string& Str) {
  size_t First{Str.find_first_not_of(' ')};
  if (First == std::string::npos) {
    return Str;
  }

  size_t Last{Str.find_last_not_of(' ')};

  return Str.substr(First, (Last - First + 1));
}

int main() {
  std::string Test{"   WINDOW_WIDTH   "};
  std::cout << "|" << Trim(Test) << "|";
}
|WINDOW_WIDTH|

Using Trim() in ProcessLine()

Now, let's see how we can use our Trim() function within the ProcessLine() function of our Config class:

#include <iostream>
#include <string>

std::string Trim(const std::string& Str) {
  // The following code is the same as the
  // previous example
  size_t First{Str.find_first_not_of(' ')};
  if (First == std::string::npos) {
    return Str;
  }

  size_t Last{Str.find_last_not_of(' ')};

  return Str.substr(First, (Last - First + 1));
}

class Config {/*...*/}; int main() { Config C; C.ProcessLine(" WINDOW_WIDTH : 800 "); }
Key: |WINDOW_WIDTH|
Value: |800|

Here we apply Trim() to both the Key and Value strings after we've extracted them from the line. This ensures that any leading or trailing spaces are removed before we process or store the values.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 79 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved