在字符串中查找单个字符
find a single char in a string
我有一个包含"0123456789?"的字符串。我想
- if first char is not ' ' or '?' and the rest is " ", return the first char
- if last char is not ' ' or '?' and the rest is " ", return the last char
- if the string is only " ", return -1
- and else, return -2
我找到了几种解决方案,但没有一个在速度和漂亮的编码方面让我满意。有人可以想到一个漂亮而优雅的解决方案,分享给我吗?!
谢谢
这
看起来像你平常的if ... else if ... ... else ...
链。 一些可能有帮助的功能:
std::string::front()
和std::string::back()
才能获得第一个或最后一个字符,std::find_if
检查空格。 如果此功能返回结束迭代器,未找到该值。
如果你可以使用C++11(如果你是学生,你可能可以;如果你在工业界工作,你可能做不到)。std::find_if
的解决方案可能是lambda。 所以:所有的字符串,除了第一个字符是空格将是:
std::find_if(
s.begin() + 1,
s.end(),
[]( char ch ) { return ! isspace( static_cast<unsigned char>( ch ) ); }
) == s.end();
对于除第一个之外的所有迭代器,或者对于所有迭代器,只需更改迭代器。
只是不要忘记在使用前检查空字符串 front()
或back()
,或在迭代器上做任何算术。
这个呢?
stringtest(string &s)
{
if(string.length()<1)
return -2
std::string begin(' ?');
if(begin.find(s.front())>1)
//test if first character of s is in begin
{
unsigned found = s.find_first_not_of(' ',1)
//checks if there are any other char then ' ' after the first char
if(found >s.length())
return s.at(0);
}
else if(begin.find(s.back())>1)
//test if last character of s is in begin
{
unsigned found = s.find_last_not_of(' ',s.length()-1);
//checks if there are any other char then ' ' before the last char
if(found !=std::string::npos)
return s.at(s.length()-1);
}
if(s.length()==1 && s.front()== ' ')
return -1
else return -2
}
相关文章:
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 为什么char不是单个字符
- C++ 字符串单个字符
- 将单个字符转换为 std::string 前缀 \x01
- 尝试一次将单个字符读取到大小不确定的数组中
- C++ 如何将字符串拆分为单个字符
- 如何在C++中将单个字符哈希为相对较小的素数?
- 如何将像'A'这样的单个字符替换为类似"10"?
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- std::bad_alloc 将文本文件中的单个字符存储到矢量C++中时
- 如何从用户那里获取单个字符,直到他输入"."或输入
- 字符串中单个字符作为数组的数据类型是什么
- 字符串中的重音,如何在单个字符中存储重音字符
- 从字符串中提取单个字符并将其转换为 int
- 如何将单个字符转换为为基本密码哈希器设置整数,C++
- 下推解析器是否扫描令牌或单个字符
- 如何定义一个从任何编码空间解析单个字符的精神 x3 解析器?
- C :占用更多内存,将单个字符作为char或字符串存储
- 如何从字符串中读取单个字符
- WM_GETTEXT只返回单个字符