Replacing a substring with another string in C
I am writing a code to replace all MACROS with its value. If my macro MAX has a value 1000, And in the code, it must be replaced with 1000.(I am assuming a case that if the MACROS are the first word in a line, then in that line MACROS will not we replaced, and that case will we be handled differently.
//Code to replace MACROS BY THEIR VALUES
//line contains the actual one line of the code.
//line is initialized to contain as maximum number of charectos(say 100).
//SrcStr is the macro and destStr is its value.
//This block will be looped for all lines.
char* p;
p = strstr(line,srcStr);
if(p != NULL) //if the srcString is found
{
if(strlen(p) != strlen(line)) //special case
{
if( isalnum(*(p-1)) == 0 && isalnum( *(p+strlen(srcStr)))==0 )
// if the next char and prev char to our macro is not a alphabets or digits
{
/*As answered by medo42 (below)*/
memmove(p+strlen(destStr), p+strlen(srcStr),strlen(p+strlen(srcStr)+1);
memcpy(p,destStr,strlen(destStr));
}
}
开发者_如何学Go else
{/* handle differently*/}
}
Since I'm using memmove
and memcopy
for the first time, I'm in doubt whether the above code is stable and works properly.
Is the above code correct? And is the above code stable for all cases of inputs?
I see at least three problems:
- memmove shouldn't use
sizeof(p)
which is always going to be fixed (say 4), it should usestrlen(line) - (p + strlen(p) - line)
- You need to handle the case where replacing the macro increases the length of the line beyond 100
- You need to handle cases where the macro label is surrounded by symbols. i.e., _MACRO_ is not the same as MACRO.
if(strlen(p) != strlen(line))
Why not simply use if(p != line)
here? That should be equivalent, easier to understand and faster (strlen scans the entire string).
isalnum(...) == 0
Personal preference maybe, but I'd write that expression as !isalnum(...)
since it's easier to understand the meaning this way.
memmove(p+(strlen(destStr)-strlen(srcStr)),p,sizeof(p));
This looks wrong to me. It will move a number of characters depending on your pointer size, which makes no sense, and if srcStr is longer than destStr, the destination of the move might be a position before the start of the line buffer. If you want to move the remainder of the line to adjust for the changed length, try this: memmove(p+strlen(destStr), p+strlen(srcStr), strlen(p+strlen(srcStr)+1);
The +1 is important to move the null terminator as well. Of course, you need to ensure that the line buffer actually provides enough space.
精彩评论