Home > OS >  iterate char by char through vector of strings
iterate char by char through vector of strings

Time:09-23

I want to iterate char by char in a vector of strings. In my code I created a nested loop to iterate over the string, but somehow I get an out of range vector.

 for ( int r = 0; r < userDataCheck.size(); r  ){
            if ((userDataCheck.at(r) == 'a') || (userDataCheck.at(r) == 'A') || (userDataCheck.at(r) == 'e') || (userDataCheck.at(r) == 'E') || (userDataCheck.at(r) == 'i') || (userDataCheck.at(r) == 'I') || (userDataCheck.at(r) == 'o') || (userDataCheck.at(r) == 'O') || (userDataCheck.at(r) == 'u') || (userDataCheck.at(r) == 'U')){
                allVows.push_back(userData.at(r));
            }
            else if ((userDataCheck.at(r) >= 'A' && userDataCheck.at(r) <= 'Z') || (userDataCheck.at(r) >= 'a' && userDataCheck.at(r) <= 'z')){
                allCons.push_back(userData.at(r));
            }
            else {
                continue;;
            }
    }

CodePudding user response:

The error here is in these lines:

allVows.push_back(userData.at(r));
allCons.push_back(userData.at(r));

the r variable is your index into the current string, but here you're using it to index into the vector, which looks like a typo to me. You can make this less error prone using range-for loops:

for (const std::string& str : userData) {
    for (char c : str) {
        if (c == 'a' || c == 'A' || ...) {
            allVows.push_back(c);
        }
        else if (...) {
            ....
        }
    }
}

which I hope you'll agree also has the benefit of being more readable due to less noise. You can further simplify your checks with a few standard library functions:

for (const std::string& str : userData) {
    for (char c : str) {
        if (!std::isalpha(c)) continue; // skip non-alphabetical
        char cap = std::toupper(c); // capitalise the char
        if (cap == 'A' || cap == 'E' || cap == 'I' || cap == 'O' || cap == 'U') {
            allVows.push_back(c);
        }
        else {
            allCons.push_back(c);
        }
    }
}
  •  Tags:  
  • c
  • Related