在子的C中列出的位置删除子 [英] Remove a substring in C given positions of substring

查看:128
本文介绍了在子的C中列出的位置删除子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个的char *例如包含20个字符。我想从删除每一个字符例如[5] 例如[10] ,然后修复了数组,这样例如[11] 来之后例如[4]

Let's say I have a char *example that contains 20 chars. I want to remove every char from example[5] to example[10] and then fix up the array so that example[11] comes right after example[4].

基本上移位删除区之后的所有字符时被删除的区域开始。

Basically shifting all the characters after the deleted region to when the deleted region started.

任何想法?

编辑:我觉得可能是使用的memcpy的方法吗?但我不知道该怎么做。

I think there might be a way using memcpy? But I'm not sure how to do it.

推荐答案

您不能使用的memcpy()可靠,因为那里的源和目标之间的重叠;您可以使用 memmove与()。既然你知道了长度,可以使用:

You can't use memcpy() reliably because there's overlap between the source and target; you can use memmove(). Since you know the lengths, you use:

memmove(&example[5], &example[11], (20 - 11 + 1));

记住,你需要复制得空终止。

Remember you need to copy the null terminator too.

#include <string.h>
#include <stdio.h>

int main(void)
{
    char array[] = "abcdefghijklmnopqrst";
    char *example = array;
    printf("%.2zu: <<%s>>\n", strlen(example), example);
    memmove(&example[5], &example[11], (20 - 11 + 1));
    printf("%.2zu: <<%s>>\n", strlen(example), example);
    return(0);
}

编译与C99编译器,即收益率:

Compiled with a C99 compiler, that yields:

20: <<abcdefghijklmnopqrst>>
14: <<abcdelmnopqrst>>

如果你有一个C89编译器(更确切地说,C库),你就必须在格式字符串,表示<$ C担心以Z $ C>为size_t 参数。这是最简单的删除以Z 和铸铁的结果的strlen()(无符号)

If you have a C89 compiler (more specifically, C library), you'll have to worry about the z in the format string, which indicates a size_t argument. It's simplest to remove the z and cast the result of strlen() with (unsigned).

这篇关于在子的C中列出的位置删除子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆