0

I want to write myself a function similar to PHP's str_repeat. I want this function to add specified amount of characters at the end of string.

This is a code that does not work (string argument 2 expected!)

void chrrepeat(const char &ch, string &target, const int &count) {
  for(int i=0; i<count; i++)
    strcat(target, ch);
}
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

2 Answers2

0

I don't exactly know what language is that (C++?), but you seem to be passing a char to strcat() instead of a null-terminated string. It's a subtle difference, but strcat will happily access further invalid memory positions until a null byte is found.

Instead of using strcat, which is inefficient because it must always search up to the end of the string, you can make a custom function just for this.

Here's my implementation in C:

void chrrepeat(const char ch, char *target, int repeat) {
    if (repeat == 0) {
        *target = '\0';
        return;
    }
    for (; *target; target++);
    while (repeat--)
        *target++ = ch;
    *target = '\0';
}

I made it return an empty string for the case that repeat == 0 because that's how it works in PHP, according to the online manual.

This code assumes that the target string holds enough space for the repetition to take place. The function's signature should be pretty self explanatory, but here's some sample code that uses it:

int main(void) {
    char test[32] = "Hello, world";
    chrrepeat('!', test, 7);
    printf("%s\n", test);
    return 0;
}

This prints:

Hello, world!!!!!!!
Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
0

Convert char to string.

void chrrepeat(char ch, string &target, const int count) {
  string help = "x"; // x will be replaced
  help[0] = ch;
  for(int i=0; i<count; i++)
    strcat(target, help);
}
MAumair
  • 23
  • 1
  • 4