[Browse] [Tag cloud]

Log on:
Powered by Elgg

C/C++ for Beginners :: Blog :: Removing Sub-strings

March 15, 2009

I've been trying to remove a smaller string that i know is contained within a larger string (eg. string1<string2, where string1 is within string2). The following code I've produced returns a pointer to a string. The function requires inputs of, a main string (string2) and the substring to be removed (string1).

The following code produces no errors, but a simple warning suggesting that I use strncpy_s (because its safer on windows). The program will crash after it has compiled and it doesn't say why. Here is my code:

char* delSubStr(char *string,char *target)

{

int i, index;

int sublen = strlen(target);

int strilen = strlen(string);

char *pos, *temp;

temp = (char *)calloc(sizeof(temp)+1, sizeof(temp));

pos = strstr(string,target);

index = string - pos;

while (pos!=NULL)

{

strncpy(temp,string,index);

for (i =(index+1); i <=(strilen-1); i++)

{

temp[i] = string[i+sublen+1];

//strcpy((*string+i),*(string+i+1+sublen));

//string[i] = string[i+1+sublen];

}string = NULL;

}

return (temp);

 

Can anyone suggest a better method that prevents overlap in sub-string deletion and another string pointer being made temporarily? some alternative methods I have tried withint the for-loop have been commented out. If they look more promising just say. 

Keywords: deleting, removing sub-strings, strings, sub-strings

Posted by Richard P @ C/C++ for Beginners | Share


Comments

  1. user icon

    Richard,

    Take a look at http://bytes.com/groups/c/220617-removing-substring-string

    Also, what are you doing with calloc?

    What will sizeof(temp) actually give you?

    Andrew

    Andrew Harvey on Monday, 16 March 2009, 10:31 GMT # |

You must be logged in to post a comment.

/