Problem Solving Through C (BCA) 1st Sem Previous Year Solved Question Paper 2022

Practice Mode:
14.

Write a program to copy a string from one character array to another without using any build-in string handling function.

Explanation

A string from one character array to another without using built-in string handling functions by iterating through the characters in the source array and copying them to the destination array one by one until you reach the null terminator ('\0').

#include <stdio.h>


void copyString(char *dest, const char *src) {

int i = 0;

while (src[i] != '\0') {

dest[i] = src[i];

i++;

}

dest[i] = '\0'; // Null-terminate the destination string

}


int main() {

char source[] = "Hello, World!";

char destination[20]; // Make sure the destination array is large enough


 // Call the custom copyString function to copy the source to the destination

copyString(destination, source);



printf("Source: %s\n", source);

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

 return 0;

}

In this program:

  1. We define a custom function copyString that takes a destination (dest) and a source (src) string as arguments.

  2. Inside the copyString function, we use a while loop to iterate through the characters of the source string until we reach the null terminator ('\0').

  3. For each character in the source string, we copy it to the destination string.

  4. After the loop, we explicitly null-terminate the destination string by adding a '\0' character at the end.

  5. In the main function, we call the copyString function to copy the source string to the destination string.