Write a C program to insert character into the string at the given location.
#include <string.h>
int main() {
char mystr[256], output[256];
int ch, pos, i = 0, j = 0;
/* get the input string from the user */
printf("Enter your input string:");
fgets(mystr, 256, stdin);
mystr[strlen(mystr) - 1] = '\0';
/* get the input character to insert */
printf("Enter the character to insert:");
ch = getchar();
/* get the location to insert the i/p character */
printf("Enter the location(0-%d):", strlen(mystr));
scanf("%d", &pos);
/* boundary check */
if (pos < 0 || pos > strlen(mystr)) {
printf("Boundary Value Exceeded!!!\n");
return 0;
}
/* copying characters present before the given location */
while (i < pos) {
output[j++] = mystr[i];
i++;
}
/* copying the input character at the given location */
output[j++] = ch;
/* copying the left characters */
while (mystr[i] != '\0') {
output[j++] = mystr[i];
i++;
}
output[j] = '\0';
/* print the resultant string */
printf("Resultant String: %s\n", output);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string:helo world
Enter the character to insert:l
Enter the location(0-10):3
Resultant String: hello world
Enter your input string:helo world
Enter the character to insert:l
Enter the location(0-10):3
Resultant String: hello world
No comments:
Post a Comment