-4

「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

いくつかの解決策を見つけましたが、速度と優れたコーディングの点で満足できるものはありませんでした。素敵でエレガントな解決策を考えている人は、それを私に共有できますか?!

ありがとうございました

4

2 に答える 2

1

if ... else if ... ... else ... これはいつものチェーンのように見えます。役立つかもしれないいくつかの機能:

  • std::string::front()std::string::back()最初または最後の文字を取得するには、

  • std::find_if空白をチェックします。この関数が終了イテレータを返す場合、値は見つかりませんでした。

C ++ 11を使用できる場合(学生の場合はおそらく使用できますが、業界で働いている場合はおそらく使用できません)、の最も洗練されたソリューションstd::find_ifはおそらくラムダです。したがって、最初の文字が空白である以外のすべての文字列は次のようになります。

std::find_if(
    s.begin() + 1,
    s.end(),
    []( char ch ) { return ! isspace( static_cast<unsigned char>( ch ) ); }
    ) == s.end();

最初を除くすべて、またはすべての場合、イテレータを変更するだけです。

front()またはを使用する前back()、またはイテレータで算術演算を実行する前に、空の文字列を確認することを忘れないでください 。

于 2013-01-25T10:11:44.230 に答える
0

これはどうですか?

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
} 
于 2013-01-25T10:25:06.237 に答える