-
String deletion problem
I have write a programme in order to do such a job:
if you input a string like "abc**d", it will delete the charactors in front of the stars (and the number of stars are equal to the number of charactors will be deleted), so it will return back the string as "ad".
if the stars are in front of the charactors, the programme will eliminate them, (e.g. input "***ab" will still return "ab")
but my programme had a problem, the charactors behind the stars will not insert into the list..and will not print on the screen consequently. I check it for many times and it seems no problem. could anyone do me a favor? Thx very much..
Here's my programme:
Code:
#include <stdio.h>
#include "list.h"
#include "fatal.h"
#define SIZE 10
void
PrintList( const List L )
{
Position P = Header( L );
if(IsEmpty(L))
printf( "Empty list\n" );
else
{
do
{
P = Advance( P );
printf( "%c", Retrieve( P ) );
} while( !IsLast( P, L ) );
printf( "\n" );
}
}
int
main(void)
{
List L;
Position P;
int i = 0, n, m, counter = 0;
char c[SIZE];
L = MakeEmpty( NULL );
P = Header( L );
printf("Enter a string:");
scanf("%s", c);
do
{
if(c[i] == '*')
{
i++;
}
} while (c[i] == '*');
do
{
do
{
if (c[i] == '*')
{
if (IsEmpty(L) != 1)
{
m = n - 1;
if (counter == 0)
m = i - 1;
Delete(c[m], L);
n = m;
i++;
counter++;
}
if (IsEmpty(L) == 1)
i++;
}
}while (c[i] == '*');
if (c[i] != '*')
{
Insert(c[i], L, P);
P = Advance(P);
i++;
}
}while (c[i] != '\0');
PrintList(L);
return(0);
}
The attach file list.c is the list implementation file, just copy from the textbook, no problem at all..
-
NightWalker,
It is quite difficult to see at first glance what you want your code to do because you are trying to do two things at once, you are parsing the string (with the special '*' functionality) and doing something with a list which I still don't really understand... I would recommend that you split out the parsing functionality into a seperate function before doing the whole list thing. eg.
Code:
void parseString(char in[], char out[])
{
int i, j = 0;
for (i = 0; in[i] != '\0'; i++)
{
if (in[i] == '*')
{
if (j > 0)
out[--j] = '\0';
}
else
out[j++] = in[i];
}
out[j] = '\0';
}
Then you can just add chars to your list without having to remove them again (if I have read your code right) - save a lot of messing around.
I also noticed that you never initialise n, which might make the code work a bit better... but I haven't tried it.