在字符串中查找单个字符

find a single char in a string

本文关键字:单个 字符 查找 字符串      更新时间:2023-10-16

我有一个包含"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
}