>> Is there any error in my programe please let me know .
What you showed gives the appearance of working, but it doesn't actually remove any elements from the string. There are lots of ways to go about doing it properly but I think there are two general needs. If you want to delete a single character from a string, you will end up shifting every character after the character to delete to the left once (closer to the 0 index). When you shift, you want to loop in the opposite direction of shifting so we will loop until we reach the rightmost index.
I created a helpful program so you can see the characters moving around.
Code:
#include <stdio.h>
#include <string.h>
int getint(int len)
{
int x;
do {
printf("Enter the index you want to remove.\n");
if (scanf("%d", &x) != 1) {
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) // ignore garbage
;
clearerr(stdin);
continue;
}
} while (x >= len || 0 > x);
return x;
}
void shift(char *body, int x, int len)
// Shift body to the left one space, starting at x.
{
if (body[x] == '\0') {
return; // Nothing to be done.
}
if (x == 0) {
x++;
}
for ( ; x < len; x++) {
printf("* index %d, new index %d ", x, x - 1);
if (!isprint(body[x]))
printf("character %d\n", body[x]);
else
printf("character %c\n", body[x]);
body[x - 1] = body[x];
}
body[x - 1] = '\0';
}
int main()
{
int x;
int i;
char hello[] = "Hello, world.";
int len = (int)strlen(hello);
for (i = 0; i < 3; i++) {
printf("\"%s\"\n", hello);
x = getint(len);
shift(hello, x, len);
printf("\"%s\"\n\n", hello);
}
return 0;
}
Of course, you can remove characters based on almost any criteria. More generally, you will want to focus on what you need to keep in the string, rather than deleting what you need to remove. A good way to look at an implementation of this is to look at the code for remove_if() from C++. That is the general idea. The implementation they show you merely requires understanding pointers.