C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Copy string (without strcpy())

C Program: Copy string (without strcpy())

Method 1: Using gets() function

C

#include <stdio.h>

 

int main() {

    char source[100], destination[100];

    int i;

 

    // Input source string

    printf("Enter the source string: ");

    gets(source); // Note: unsafe, use fgets() in practice

 

    // Copy characters manually

    for (i = 0; source[i] != '\0'; i++) {

        destination[i] = source[i];

    }

    destination[i] = '\0'; // Add null terminator at the end

 

    // Display copied string

    printf("Copied string: %s\n", destination);

 

    return 0;

}

Output

 
INPUT :
Enter the source string: ITDeveloper

OUTPUT 2 :
Copied string: ITDeveloper

Explanation

  1. The program takes a string as input in source.
  2. Each character of source is copied one by one into destination using a for
  3. The null character '\0' is added at the end to properly terminate the copied string.
  4. Finally, the new string is displayed.

 

C Program: Copy string (without strcpy())

Method 2: Using fgets() function

C

#include <stdio.h>

 

int main() {

    char source[100], destination[100];

    int i = 0;

 

    printf("Enter the source string: ");

    fgets(source, sizeof(source), stdin);

 

    while (source[i] != '\0' && source[i] != '\n') {

        destination[i] = source[i];

        i++;

    }

    destination[i] = '\0';

 

    printf("Copied string: %s\n", destination);

 

    return 0;

}

Output

 
INPUT :
Enter the source string: ITDeveloper

OUTPUT 2 :
Copied string: ITDeveloper

Explanation

  1. The program takes a string as input in source.
  2. Each character of source is copied one by one into destination using a for
  3. The null character '\0' is added at the end to properly terminate the copied string.
  4. Finally, the new string is displayed.