Ohhh
Ohhh

Reputation: 51

how can I multiply strings in C like I do in python?

in python you can easily type:

str = "hi"
print(str * 10)

and the output would be hi printed 10 times. I'm currently learning how to code in C and I have to do this. Can someone teach me how I can do this kind of thing in C? Thanks in advance

Upvotes: 2

Views: 1450

Answers (2)

Vishnu CS
Vishnu CS

Reputation: 853

Using for-loop is the best way to implement this.

You can just create a customized print function which will do the same thing as python does. I am just giving a prototype here.

#include <stdio.h>

void print(char *string,int n)
{
    int i;
    for(i=0;i<n;i++)
    {
     printf("%s\n",string);   
    }
}

int main()
{
    char *str="Hi";
    print(str,2);
    return 0;
}

Here second argument in the function n will tell you how many times you want to print the string.

The output will look like

Hi
Hi

Upvotes: 2

niry
niry

Reputation: 3308

Use for() loop:

Example:

#include <stdio.h>
int main() {
  char* str = "hi";
  for (int i = 0; i < 10; ++i) {
    printf("%s", str);
  }
}

And if you need to actually multiply the string (not just print n times) you can use the following mulstr(), just don't forget to test for NULL and to free():

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>

char* mulstr(char* str, size_t i) {
  size_t len = strlen(str);
  char* newstr = malloc(len * i + 1);
  if (newstr) {
    char* writer = newstr;
    for (; i; --i) {
      memcpy(writer, str, len);
      writer += len;
    }
    *writer = 0;
  } else {
    perror("malloc");
  }
  return newstr;
}

int main() {
  char* str = "hi";
  char* newstr = mulstr(str, 10);
  if (newstr) {
    printf("%s", newstr);
    free(newstr);
  }
}

Upvotes: 7

Related Questions