C Program to replication of string

Write a c program to implement the replication of string which will be given as a command line argument?

Showing Answers 1 - 6 of 6 Answers

Abhishek

  • Nov 11th, 2011
 

Code
  1. #include <stdio.h>

  2. #include <stdlib.h>

  3. #include <string.h>

  4.  char * string_repeat( int n, const char * s )

  5. {

  6.  size_t slen = strlen(s);  

  7. char * dest = calloc(n*slen+1, sizeof(char));  

  8. int i; char * p;  

  9. for ( i=0, p = dest; i < n; ++i, p += slen )

  10. {    

  11. memcpy(p, s, slen);  

  12. }  

  13. return dest;

  14. }

  15. int main()

  16. {  

  17. printf("%s

  18. ", string_repeat(5, "ha"));  

  19. return 0;

  20. }

  Was this answer useful?  Yes

saurabh singh

  • Jun 19th, 2014
 

Here is a simple code using command line argument to print multiple number of strings with "_" between them.

To check the output , type this in command prompt : filename ABC 5
OUTPUT: ABC_ABC_ABC_ABC_ABC

Code
  1.  

  2. #include<stdio.h>

  3. #include<stdlib.h>

  4.  

  5. int main(int argc, char *argv[])

  6. {

  7.         if(argc<2)

  8.         {

  9.                 printf("Enter CLA") ;

  10.                 return 0 ;

  11.         }

  12.        

  13.     printf("%s",argv[1]) ;

  14.          

  15.         int n = atoi(argv[2]) ;

  16.  

  17.     for(int i=0;i<n;i++)

  18.         printf("_%s ",argv[1]) ;

  19.         return 0 ;

  20.        

  21. }

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions