A function I created, which I refer to as string_deletion
, deletes occurrences of a specific substring and shifts the string leftwards by the length of the substring. The function accepts two parameters: the pointer to the location in the array wherein the first letter of the substring is encountered, and the length of the word.
Here is the function:
void string_deletion(char *s, int m)
{
char *index=s+m;
while(*index!=0)
{
*(index-m)=*(index++);
}
*(index-m)=0;
}
The function shifts all the characters after the substring leftwards by an amount dependent on the length of the substring, which has been denoted by m
. I have set the index
pointer to point to the character that occurs immediately after the occurrence of the substring, and this is the mark from where the shifting commences. The loop is executed until a NUL
character is encountered, after which it exits the loop. At the culmination, the NUL
is appended to the end of the string.
Whereas the other parts of the main code work seamlessly, invoking this specific function, as and when necessary, makes the program cease working and it yields an error. What explains this?
Here's the complete code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<limits.h>
int string_len(char *s)
{
int i=0;
char *m=s;
while(*m!=0)
{
i++;
m++;
}
return i;
}
void word_enter(char *word_search)
{
char r;
char *m=word_search;
while((r=getchar())!=EOF)
{
if(r=='\n')
{
*m=0;
break;
}
else
{
*(m++)=r;
}
}
}
void string_disp(char *s)
{
char *d=s;
while(*d!=0)
{
putchar(*(d++));
}
}
int string_comp(char *s, char *m)
{
int stringlength_one=string_len(s);
int stringlength_two=string_len(m);
char *s_one=s;
char *s_two=m;
if(stringlength_one!=stringlength_two)
{
return 1;
}
else
{
while(*s_one!=0)
{
if(*s_one!=*s_two)
{
return 1;
}
s_one++;
s_two++;
}
}
return 0;
}
void string_deletion(char *s, int m)
{
char *index=s+m;
while(*index!=0)
{
*(index-m)=*(index++);
}
*(index-m)=0;
}
void string_search(char *s,char *d)
{
char *m=s;
char word_buffer[20];
char *buffer_index=word_buffer;
while(m!=&s[string_len(s)-string_len(d)+1])
{
buffer_index=word_buffer;
if(*m==*d)
{
int i=0;
char *r=m;
while(i<=string_len(d) && *r!=0)
{
*(buffer_index++)=*(r++);
i++;
}
*buffer_index=0;
if(string_comp(word_buffer,d)==0)
{
printf("\nInvoking deletion sequence\n");
string_deletion(m,string_len(d));
}
}
m++;
}
}
int main(void)
{
int pos;
char main_string[100],word[20];
printf("Enter the main string: ");
word_enter(main_string);
printf("\nEnter the string you wish to delete: ");
word_enter(word);
string_search(main_string,word);
string_disp(main_string);
exit(EXIT_SUCCESS);
}