Q:

C program to copy one string to another and count copied characters

belongs to collection: C String Programs

0

C program to copy one string to another and count copied characters

Given a string and we have to copy it in another string, also find and print the total number of copied characters using C program.

Example:

    Input:
    String 1 (Input string): "This is a test string"

    Now, we will copy string 1 to the string 2
    Output:
    String 1: "This is a test string"
    String 2: "This is a test string"
    Total numbers of copied characters are: 21

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to copy one string to another string and find total number of copied character in C

#include <stdio.h>

//function to copy the string
int copy_string(char *target, char *source)
{
	//variable tp store length, it will also work
	//as loop counter
	int len=0;
	
	//loop to run from 0 (len=0) until NULL ('\0')
	//not found
	while(source[len] != '\0')
	{
		target[len] = source [len];
		len++;
	}
	//assign NULL to the target string
	target[len] = '\0';
	
	//return 'len'- that is number of copied characters
	return len;
}

//main code
int main()
{
	//declare and assign string1 to be copied
	char str1[]="This is a test string";
	//declare string 2 as target string
	char str2[30];
	//variable to store number of copied characters
	//that will be returned by the copy_string()
	int count;
	
	//calling the function
	count = copy_string(str2,str1);
	
	//printing values
	printf("Source string (str1): %s\n",str1);
	printf("Target string (str2): %s\n",str2);
	printf("Copied characters are: %d\n",count);
	
	return 0;	
}

Output

Source string (str1): This is a test string
Target string (str2): This is a test string
Copied characters are: 21	

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to remove all spaces from a given string... >>
<< C program to read n strings and print each string\...