Remove characters from a string in C [duplicate]
Possible Duplicate:
Remove characters from a string in C
I'm creating a small todo application in C and I'd like to remove *
then a space
from a string I'm looping over each line then checking if the lineNumber
is the one passed in to the function then I'd wondering how to remove the characters from that line, Heres the code where I loop over the lines
while (fgets(line, sizeof line, oldTodoFile)) {
len = strlen(line);
if (len && (line[len - 1] != '\n')) {} else {
lineNumber++;
if (lineNumber == todoNumber) {
// remove *[space]
} else {
fprintf(todoFile);
开发者_如何学Go }
}
Sounds like you're asking how to remove a leading '* '
from the beginning of a string. You have two options:
You can either just move each character two spaces back, something like:
if(startsWithStarSpace) { int i; for(i = 2; i < len; ++i) str[i-2] = str[i]; str[i] = '\0'; }
Or if your string is dynamically allocated, you can just move the pointer forward by two characters (making sure to save your old pointer to
free()
later).
a simple way to do this (note i know this is not the best way, i'm sure there is lots of standard functions for this) would be:
if(lineNumber == todoNumber) {
char buff[len];
char* bptr = buff;
char* lptr = line;
for(;lptr!=NULL;) {
if(*lptr!='*')
*bptr++ = *lptr++
else{
lptr++;lptr++; /*skip over * and space */
}
}
strcpy(line,buff); /* replace line with updated version */
}
Like I said, not the best solution but its one way to do it.
精彩评论