In C++, there is no built-in string trim function, but we can write one using find_first_not_of and find_last_not_of. For this lesson, a trim() helper function has been provided for you:
// trim() removes leading and trailing spaces
string s = " hello ";
string result = trim(s);
// result == "hello"
Here is how a trim function works internally:
string trim(const string& s) {
int start = 0, end = s.size() - 1;
while (start <= end && s[start] == ' ') start++;
while (end >= start && s[end] == ' ') end--;
return s.substr(start, end - start + 1);
}
Assignment
Follow the Coding Tutorial and use the trim() helper to strip whitespace from s!
Hint
Use trim(s) and assign the result to result.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
