C++ std::string::find_first_not_of
Determine whether a field supplies any content after ignoring ordinary whitespace.
A simple example
std::string::find_first_not_of
- Start with " "
- Do this Check for blank text
- Result Yes
#include <iostream>
#include <string>
int main() {
const std::string value = " ";
std::cout << ((value.find_first_not_of(" \t\r\n") == std::string::npos) ? "yes" : "no") << "\n";
return 0;
}
yes
Syntax
value.find_first_not_of(" \t\r\n") == std::string::npos
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonCheck an attendance comment
A form accepts an optional note typed or pasted by a customer or student. Decide whether the field contains meaningful text before displaying it to the person who will act on the request.
#include <iostream>
#include <string>
int main() {
const std::string value = " \t ";
std::cout << ((value.find_first_not_of(" \t\r\n") == std::string::npos) ? "yes" : "no") << "\n";
return 0;
}
yes
Spaces and a tab supply no comment.
Check an aisle request
A traveler types a seating preference with padding around the word aisle. Check whether the preference still contains useful text after the surrounding whitespace is removed.
#include <iostream>
#include <string>
int main() {
const std::string value = " aisle ";
std::cout << ((value.find_first_not_of(" \t\r\n") == std::string::npos) ? "yes" : "no") << "\n";
return 0;
}
no
The word aisle is meaningful after trimming.
Review a space-only answer
A student pressed the space bar three times before submitting a response. The submission form treats whitespace-only text as a blank response. Which status should the reviewer see?
What to watch for
Blankness is a field policy. Choose which Unicode whitespace characters the application should ignore.