如何使用 C 中的 baskspace 从字符串中删除字符?
你能给我一个从c中的字符数组中删除字符的例子吗? 我尝试了太多,但没有达到我想要的,
这就是我所做的:
int i;
if(c<max && c>start) // c is the current index, start == 0 as the index of the start,
//max is the size of the array
{
i = c;
if(c == start)
break;
arr[c-1] = arr[c];
}
printf("%c",arr[c]);
can you give me an example of deleting characters from an array of characters in c?
I tried too much, but i didn't reach to what i want
That is what i did:
int i;
if(c<max && c>start) // c is the current index, start == 0 as the index of the start,
//max is the size of the array
{
i = c;
if(c == start)
break;
arr[c-1] = arr[c];
}
printf("%c",arr[c]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C 中的字符数组不允许删除条目。您所能做的就是移动数据(例如使用 memmove)。例子:
A character array in C does not easily permit deleting entries. All you can do is move the data (for instance using memmove). Example:
您有一个字符数组 c:
您想要一个仅包含“abcdefg”(加上空终止符)的不同数组。你可以这样做:
使用 memcpy 或 memmove 有更有效的方法来做到这一点,并且它可以变得更通用,但这就是本质。如果您真的关心速度,您可能应该创建一个不包含您不需要的字符的新数组。
You have an array of characters c:
You want a different array that contains only "abcdefg" (plus the null terminator). You can do this:
There are more efficient ways to do this using memcpy or memmove, and it could be made more general, but this is the essence. If you really care about speed, you should probably make a new array that doesn't contain the characters you don't want.
这是一种方法。您无需将字符删除并重新排列剩余的字符(这很痛苦),而是将要保留的字符复制到另一个数组中:
Here's one approach. Instead of removing characters in place and shuffling the remaining characters (which is a pain), you copy the characters you want to keep to another array:
string = HELLO \0
string_length = 5 (或者如果您不想在此调用之外缓存它,则只需在内部使用 strlen
如果您想删除 'E'
副本到 'E' 位置(string + 1),
remove_char_at_index = 1从第一个 'L' 位置 (string + 1 + 1)
4 个字节(想要得到 NULL),所以 5 - 1 = 4
string = H E L L O \0
string_length = 5 (or just use strlen inside if you don't want to cache it outside this call
remove_char_at_index = 1 if you want to delete the 'E'
copy to the 'E' position (string + 1)
from the first 'L' position (string + 1 + 1)
4 bytes (want to get the NULL), so 5 - 1 = 4