我想检查20个字符的字符串对象中是否只有空字符(值为零)。我的尝试:

string subString;
subString = fileBuffer.substr(origin, origin+20);

if(strCompare.compare("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0") == 0)
    cout<<"string is empty"<<endl;
else
    cout<<"string is not empty"<<endl;

我确定为subString分配了20个null字符,但是,程序仅输出“字符串不为空”。我也尝试了其他方法,例如将compare参数设为“”或NULL无效。有人可以向我指出任何明显的错误或正确的方法吗?我真的很感激。

最佳答案

这个问题:

 if(strCompare.compare("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")

是从C样式字符串构造的字符串将为空。您需要显式构造一个字符串,并提供大小。单程:
 if( strCompare.compare(
     std::string( "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20 ) == 0 )

或更短:
 if( strCompare.compare(
     std::string( 20, 0 ) == 0 )

关于c++ - 检查字符串对象是否只有空字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2165315/

10-10 21:31
查看更多