Computer Science, asked by ashishjyadav2821, 1 year ago

Write a program to insert a character at a given position in a given string

Answers

Answered by StormAngler
1
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);
}
Answered by Anonymous
31

Answer:

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