Skip to main content

Command Palette

Search for a command to run...

Copying Strings

Published
1 min readView as Markdown

Program to copy string 1 to string 2:

#include <stdio.h>
int main() {
    char s1[100], s2[100], i;
    printf("Enter string s1: ");
    fgets(s1, sizeof(s1), stdin);

    for (i = 0; s1[i] != '\0'; ++i) {
        s2[i] = s1[i];
    }

    s2[i] = '\0';
    printf("String s2: %s", s2);
    return 0;
}

Output:

strcpy and strncpy

char *strcpy(char *dest, const char *src)

Parameters

  • dest − This is the pointer to the destination array where the content is to be copied.

  • src − This is the string to be copied.

char *strncpy(char *dest, const char *src, size_t n)

Parameters

  • dest − This is the pointer to the destination array where the content is to be copied.

  • src − This is the string to be copied.

  • n − The number of characters to be copied from source.

Both strcpy() and strncpy() return the pointer to the copied string.

Program:

#include <stdio.h>
#include <string.h>
#define MAX 50
int main() {
  char str1[MAX] = "Hello World!";
  char str2[MAX];

  // Copy str1 to str2
  strcpy(str2, str1);

  // Print str2
  printf("%s\n\n", str2);

  char str3[MAX];
  strncpy(str3,str1,5);
  puts(str3);

  return 0;
}

Output:

16 views

More from this blog

P

Programming Tutorials

89 posts