Computer Science, asked by rohanmalhotra9490, 1 year ago

Write a c program to insert a character in a string

Answers

Answered by KartikSharma13
0
int i, j, count = 0, pos, flag = 0; here is the c program to insert a character in a string
Answered by Anonymous
52

Explanation:

I am using C as the programming language

#include<studio.h>

void main(){

char mystring[251]; // We will be accepting a character array of 250 characters from the user

printed('Please enter the string of max 250 characters: ');

scanf('%s', mystring);

// Getting the position from the user

int index;

char mychar;

printf('\nInsert the position you want to insert an new character: ');

scanf('%d', &index);

printf('\nEnter the new character you want to insert:');

scanf('%c', &mychar);

// Iterating through the array to the index - 1 position since computers start numbering array elements from 0.

char newString[251]; // We will be saving the characters from position index - 1 to the end of the string in this array. The size is one character more than the original string size

int i = 0;

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

if(i < index - 1){

// We will copy elements to newString

newString[i] = mystring[i];

i++;

}else if(i == index - 1){

// We will copy the user input character in newString

newString[i] = mychar;

}else{

// We will copy the remaining characters to newString

newString[i+1] = mystring[i];

// The index of newString is i+1 because it has one more character than mystring

i++;

}

}

// Now display the string to the user

printf('\nThe new string is as follows:\n');

printf('%s\n', newString);

}

Similar questions