C (programming language)

c program to copy one string to another string without using library function

Understanding the Task

  • Goal: Create a C program that replicates a string into another string manually, avoiding built-in functions like strcpy.
  • Key Concepts:
    • Character arrays: Strings are stored as character arrays.
    • Loops: for loop for iterating through characters.
    • Null terminator: A character with value 0 (\0) marking the end of a string.

Step-by-Step Guide

1. Header Inclusion

C

#include <stdio.h>
  • Explanation: Includes the standard input/output library for functions like printf.

2. Main Function

C

int main() {
    // Code statements here
    return 0;
}

3. Declare String Variables

C

char str1[100], str2[100];  // Declare char arrays with sufficient capacity

4. Get Input String

C

printf("Enter a string: ");
fgets(str1, 100, stdin);  // Use fgets to read a string safely
  • Explanation: fgets is preferred over scanf for strings to avoid buffer overflows.

5. Copy String Character by Character

C

int i = 0;
while (str1[i] != '\0') {
    str2[i] = str1[i];
    i++;
}
str2[i] = '\0';  // Add null terminator to the copied string
  • Explanation:
    • The loop iterates until the null terminator is encountered in str1.
    • Each character from str1 is copied to the corresponding position in str2.
    • The null terminator is manually added to str2 to mark its end.

6. Print the Copied String

C

printf("Copied string: %s", str2);

7. Complete Code

C

#include <stdio.h>

int main() {
    char str1[100], str2[100];

    printf("Enter a string: ");
    fgets(str1, 100, stdin);

    int i = 0;
    while (str1[i] != '\0') {
        str2[i] = str1[i];
        i++;
    }
    str2[i] = '\0';

    printf("Copied string: %s", str2);

    return 0;
}

Key Points

  • Manual string copying offers control and understanding of string manipulation.
  • Ensure sufficient array sizes to accommodate potential string lengths.
  • Always add the null terminator to the copied string to ensure proper string handling.
  • Consider using fgets or getline for safer string input compared to scanf.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button