开发者

Is there a good way to remove a character from a string without copying all the characters following it?

// The first example:
char text[] = "henri";
char *p;
p = text;
*(p + 1) = 'E'; // Output = hEnri
// Now If we want to remove the "e" ie hnri, we would go for?????
     *(p + 1)=????? 

The obviou开发者_C百科s answer is to copy the rest of the array "back" one position. But this seems... unpleasant. Surely there is some better way?


Copying is the best solution and really the only solution when you're removing elements from an array. (You can special case the element at the end of the array, but that's it.) I don't understand why it's so terrible.

You need to do one of two things. Both involve some copying.

1) Copy the 'n' to where the 'E' is, the 'r' to where the 'n' is, the 'i' to where the 'r' is, and then null terminate it.

2) Copy the 'h' to where the 'E' is and then always use the pointer to the 'h's new location. This may not always be an option.


*++p = 'h';
puts(p);


You'd have to move all the remaining characters up one. There's no way to say "skip this char".

while (*p)
{
    *p = *p++;
}

edit: ugh, how did I make that mistake? Now fixed. p will still be non-null at the end of the string, but *p will not.


move the characters down by 1 after it (including the null at the end)

you'll end up with two nulls at the end, by the way.


This is not copying the array. I'm moving the data within the same array.

for (p = text + 1; *p != '\0'; ++p) {
  *p = *p + 1;
}

A hackier solution is to put the 'h' where the 'e' was, and return a pointer to the new beginning.

*p + 1 = *p;
p = p + 1;


This should do it:

memmove(p+1, p+2, 4);

We move four characters because we want to copy the null terminator as well.


There is no way to remove anything from a C string without copying the following characters to fill in the hole.

But you could change your data structure and use something other than a string. For example, you could use an array or linked list of string pieces. This is sometimes called a "rope."

Of course, when you need to pass the data to some other function that expects a C string you have to copy out the entire thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜