C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Programming Tips & Tricks » C - Tips & Tricks

Replacing a part of string in C

By: IncludeHelp, on 23 JAN 2017

Let suppose there is a string "This is a computer" and you want to replace string from index 10 with "Hello" i.e. you want to replace "compu" with "Hello".

Then the string will be "This is Helloter".

Here is the statement to replace string



memcpy() - This is the library function of string.h, which is used to copy fixed number of bytes, memcpy() does not insert NULL, so this function is safe to replace the string.

str+10 – This is the address of 10th Index of character array (string) str.

"Hello" - String which will be inserted from index 10.

5 - Number of bytes to be copied.

Consider the program, which demonstrate the use of memcpy() to replace string.

#include <stdio.h>
#include <string.h>

int main()
	char str[]="This is a computer";
	printf("Original string: %s\n",str);
	printf("Modified string: %s\n",str);
	return 0;


    Original string: This is a computer 
    Modified string: This is a Helloter