C++检查字符串是空格还是null

C++ check if string is space or null

本文关键字:null 空格 C++ 字符串 检查      更新时间:2023-10-16

基本上,我在文件的某些行中有一个空白字符串" "或空白块或""为空,我想知道C++中是否有一个函数可以检查这一点。

*注意:*作为一个附带问题,在C++中,如果我想分解字符串并检查它的模式,我应该使用哪个库?如果我想自己编写代码,我应该知道哪些基本函数来操作字符串?有什么好的推荐信吗?

bool isWhitespace(std::string s){
    for(int index = 0; index < s.length(); index++){
        if(!std::isspace(s[index]))
            return false;
    }
    return true;
}
std::string str = ...;
if (str.empty() || str == " ") {
    // It's empty or a single space.
}
 std::string mystr = "hello";
 if(mystr == " " || mystr == "")
   //do something

在分解字符串时,std::stringstream可能会有所帮助。

"在文件的某些行中"没有空字符串。

但是你可以有一个空字符串,也就是空行。

您可以使用例如std::string.length,或者如果您更喜欢C,则可以使用strlen函数。

为了检查空白,isspace函数很方便,但请注意,对于char字符,应将自变量转换为unsigned char,例如即兴、

bool isSpace( char c )
{
    typedef unsigned char UChar;
    return bool( ::isspace( UChar( c ) ) );
}

干杯&hth。,

由于您还没有指定字符>0x7f的解释,我假设ASCII(即字符串中没有高位字符)。

#include <string>
#include <cctype>
// Returns false if the string contains any non-whitespace characters
// Returns false if the string contains any non-ASCII characters
bool is_only_ascii_whitespace( const std::string& str )
{
    auto it = str.begin();
    do {
        if (it == str.end()) return true;
    } while (*it >= 0 && *it <= 0x7f && std::isspace(*(it++)));
             // one of these conditions will be optimized away by the compiler,
             // which one depends on whether char is signed or not
    return false;
}

如果您想要进行模式检查,请使用regexp。