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?
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.
Parsing Data using std::string
Learn how to read, parse, and use config files in your game using std::string
and SDL_RWops