检查彼此相邻的两个下划线

时间:2014-02-04 21:18:38

标签: c++

我的代码应该检查两个下划线是否彼此相邻,在字符串的开头或结尾以及更多其他规则.....问题是当代码在整个字符串中找到2个下划线时,它打印Chyba但它不应该。只有当它找到类似abc__abc之类的内容时,它才能打印Chyba,但它的工作原理如abc_abc_abc>> chyba ......任何解决方案?

 void Convert(string input){
    string output = "";
    string flag = "";
    bool underscore = false;
    bool uppercase = false;
    if ( islower(input[0]) == false){
        cout << "Chyba!" <<endl;
        return;
    }

    for (int i=0; i < input.size(); i++){
        if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
            cout << "Chyba!" <<endl;
            return;
        }
        if (islower(input[i])){
            if (underscore){
                underscore = false;
                output += toupper(input[i]);
            }
            else
                output += input[i];

        }
        else if (isupper(input[i])){
            if (flag == "C" || uppercase){
                cout << "Chyba!"<<endl;
                return;
            }
            flag = "Java";
            output += '_';
            output += tolower(input[i]);

        }
        else if (input[i] == '_'){
            if (flag == "Java" || underscore){
            cout << "Chyba!" <<endl;
            return;
            }
            flag = "C";
            underscore = true;
        }

    }


    for (int i=input.size()-1; i >=0; i--){
      if (input[i] == '_'){
            if (flag == "Java" || underscore){
            cout << "Chybaaa!" <<endl;
            return;
            }
            flag = "C";
            underscore = true;
        }
    }
cout << output <<endl;
} 

1 个答案:

答案 0 :(得分:9)

bool containsAdjacentUnderscores = std::search_n(begin(input), end(input), 2, '_') != end(input);