I’m iterating through an array of chars to do some manipulation. I want to “skip” an iteration if there are two adjacent characters that are the same.
e.g. x112abbca
skip———-^
I have some code but it’s not elegant and was wondering if anyone can think of a better way? I have a few case‘s in the switch statement and would be happy if I didn’t have to use an if statement inside the switch.
switch(ent->d_name[i])
{
if(i > 0 && ent->d_name[i] == ent->d_name[i-1])
continue;
case ' ' :
...//code omited
case '-' :
...
}
By the way, an instructor once told me “avoid continues unless much code is required to replace them”. Does anyone second that? (Actually he said the same about breaks)
Put the
ifoutside theswitch.While I don’t have anything against using
continueandbreak, you can certainly bypass them this time without much code at all: simply revert the condition and put the whole switch statement within the if-block.Answering the rectified question: what’s clean depends on many factors. How long is this list of characters to consider: should you iterate over them yourself, or perhaps use a utility function from
<algorithm>? In any case, if you are referring to the same character multiple times, perhaps you ought to give it an alias: