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

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.