C++ 在子字符串中查找空格
C++ find whitespaces in substring
我想知道如何在 C++ 中找到子字符串中的空白或空格。例如:
string str = "( )"; // or str = "()"
在这里,我想确保括号之间始终有内容。函数 isspace() 只需要一个字符,所以我必须循环搜索。有没有更好的方法来做到这一点?感谢您的帮助。
您可以使用 std::string::find()
查找 (
和 )
字符,然后使用 std::string::find_first_not_of()
检查这些索引之间的任何 non-whitespace 字符。
string str = "( )"; // or str = "()"
string::size_type idx1 = str.find("(");
if (idx1 != string::npos) {
++idx1;
string::size_type idx2 = str.find(")", idx1);
if (idx2 != string::npos) {
string tmp = str.substr(idx, idx2-idx1);
string::size_type idx3 = tmp.find_first_not_of(" \t\r\n");
if (idx3 != string::npos) {
...
}
}
}
我想知道如何在 C++ 中找到子字符串中的空白或空格。例如:
string str = "( )"; // or str = "()"
在这里,我想确保括号之间始终有内容。函数 isspace() 只需要一个字符,所以我必须循环搜索。有没有更好的方法来做到这一点?感谢您的帮助。
您可以使用 std::string::find()
查找 (
和 )
字符,然后使用 std::string::find_first_not_of()
检查这些索引之间的任何 non-whitespace 字符。
string str = "( )"; // or str = "()"
string::size_type idx1 = str.find("(");
if (idx1 != string::npos) {
++idx1;
string::size_type idx2 = str.find(")", idx1);
if (idx2 != string::npos) {
string tmp = str.substr(idx, idx2-idx1);
string::size_type idx3 = tmp.find_first_not_of(" \t\r\n");
if (idx3 != string::npos) {
...
}
}
}