C++检查字符串是空格还是null
C++ check if string is space or null
基本上,我在文件的某些行中有一个空白字符串" "
或空白块或""
为空,我想知道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。
相关文章:
- 2D数组来自文本输入,中间有空格
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 如何在 c++ 中'NULL'字符串
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- c++使用foreach使数组为null
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 当使用通配符和null指针调用函数时,对输出的说明
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 移除前面有空格的前2个字符串
- 如何在映射中返回null
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- C++检查字符串是空格还是null