Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First time through idiom

This is a classic problem where a list of elements must be processed but the first must be handled differently from the rest. For example printing a string so that each two characters have a dash between.

Here is a fairly horrible example

    char *text = "hello";

    for (int i = 0; i < strlen(text); i++) {

            if (i == 0) {
                    printf("%c", text[i]);
            } else {
                    printf("-%c", text[i]);
            }
    }

Output:

h-e-l-l-o

First of all, is there a common name for this situation so I can look it up properly?

Second, of course, what is a better way of dealing with this kind of problem? "Better" being either fewer lines of code, faster runtime or lower memory overhead (preferably a happy compromise between them).

Post example code in any language.

like image 727
user2675345 Avatar asked Dec 05 '25 05:12

user2675345


1 Answers

Sticking with the original C you've written, it's generally best when possible to leave special cases out of the loop, as loops are meant for repetition of the same task. I would write the code as:

char *text = "hello";

printf("%c", text[0]);
for (int i = 1; i < strlen(text); i++){
    printf("-%c", text[i]);
}

Often the last might also be a special case in which case, you would loop until strlen(text) - 1. Of course, if you're using a language with API's that specifically deal with this problem, then use them like in @TylerEaves answer. I'm not aware of any specific name for this kind of problem, but whenever you adjust loop bounds, always be careful of an off-by-one error.

like image 75
DPenner1 Avatar answered Dec 09 '25 07:12

DPenner1