user422100 user422100 - 3 months ago 11
C Question

how repeat a string in language C

how I do to repeat a string?
something like "hello world" * 3
the output "hello world hello world hello world"

Answer

In your source code, without much processing, probably the easiest way is with:

#define HI "hello world"
char str[] = HI " " HI " " HI;

This will declare a string of the requested value:

"hello world hello world hello world"

If you want code that will do it, you can use something like:

char *repeatStr (char *str, size_t count) {
    if (count == 0) return NULL;
    char *ret = malloc (strlen (str) * count + count);
    if (ret == NULL) return NULL;
    strcpy (ret, str);
    while (--count > 0) {
        strcat (ret, " ");
        strcat (ret, str);
    }
    return ret;
}

Now keep in mind this can be made more efficient - multiple strcat operations are ripe for optimisation to avoid processing the data over and over (a). But this should be a good enough start.

You're also responsible for freeing the memory returned by this function.


(a) Such as with:

// Like strcat but returns location of the null terminator
//   so that the next myStrCat is more efficient.

char *myStrCat (char *s, char *a) {
    while (*s != '\0') s++;
    while (*a != '\0') *s++ = *a++;
    *s = '\0';
    return s;
}

char *repeatStr (char *str, size_t count) {
    if (count == 0) return NULL;
    char *ret = malloc (strlen (str) * count + count);
    if (ret == NULL) return NULL;
    *ret = '\0';
    char *tmp = myStrCat (ret, str);
    while (--count > 0) {
        tmp = myStrCat (tmp, " ");
        tmp = myStrCat (tmp, str);
    }
    return ret;
}