How to "skip" spaces while iterating over a string

Viewed 157

Hello noob question here. I'm learning strings and am currently writing a program that takes a string and alternates caps with the first letter starting as lower case. The problem I'm having is that if the string has spaces, it messes up the alternating pattern. I was wondering if there was a way to skip the spaces or ignore them? heres what I have so far.

#include<string>
#include <iostream>

std::string convertToAltCaps(std::string str) {

    for (int i = 0; i < str.length(); i++) {

        if (str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'a' && str[i] <= 'z') {

            if (i % 2 != 0) {
               str[i]= toupper(str[i]);
            }
            else {
                str[i]=tolower(str[i]);
            }
        }

            
    }
    return str;
}
1 Answers

The remainder if (i % 2 != 0) check will, as you've noticed, not be able to do a good job at this since it's supposed to "reset" every time a new word starts.

One way could be to keep a bool for when it's time to flip to lower or upper case. Anytime a whitespace is encountered, you reset that bool.

Example:

std::string convertToAltCaps(std::string str) {
    bool lower = true;

    for (char& ch : str) {                         // range-based for loop
        // use unsigned char with cctype functions:
        auto uch = static_cast<unsigned char>(ch);

        if (std::isalpha(uch)) {                   // a-z and A-Z (in "C" locale)
            if (lower)
                ch = std::tolower(uch);
            else
                ch = std::toupper(uch);
            lower = !lower;                        // toggle

        } else if (std::isspace(uch)) {
            lower = true;                          // next alphabetic should be lower
        }
    }
    return str;
}

Demo

Related