C - Insert Text at beginning of Given String using C Program.


IncludeHelp 14 August 2016

In this code snippet you will learn how to insert any text (given or entered) at the beginning of any string (given or entered).

In this example we will read a string and read text, that will be inserted at beginning of entered first string, program will merge (insert) second string (text that you want to insert) at the beginning of first string (actual string).

C Code Snippet – Insert Text at Beginning of any String

/*C - Insert Text at beginning of 
Given String using C Program.*/

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

int main(){
	char str1[100];
	char str2[100];
	char temp[100];
	
	printf("Enter string: ");
	gets(str1);
	printf("Enter text to insert: ");
	gets(str2);
	
	//copy first string in temp variable
	memcpy(temp,str1,sizeof(str1));

	//copy second string first
	memcpy(str1,str2,strlen(str2));
	memcpy(str1+strlen(str2),temp,strlen(temp)+1);

	printf("String is: %s\n",str1);
	
	return 0;	
}

    Enter string: C programming.
    Enter text to insert: Programming Language -
    String is: Programming Language -C programming.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.