gpt4 book ai didi

c - 缩短 C 字符串以从第一次出现的内容中排除更多字符

转载 作者:行者123 更新时间:2023-11-30 15:43:11 25 4
gpt4 key购买 nike

我有一个 C 字符串,我想缩短它,以便它从第一次出现的“$”处被剪切。这是我的代码:

int char_search(char exp[], int s, char what) {
int i, occurrence=-1;
for (i=0; i < s && occurrence == -1; ++i)
if (exp[i] == what)
occurrence = i;

return occurrence;
}

int shorten(char *exp, int maxlength, char *exp_new) {
int l, i;
l = char_search(exp, maxlength, '$');
exp_new = (char *) malloc((l+1)*sizeof(char));
exp_new[l] = '\0';
for (i = 0; i<l; i++)
exp_new[i] = exp[i];

return l;
}

问题是它开始覆盖exp_new指针地址,并且只将第一个字符复制到实际数组中。另外,exp_new 由于某种原因返回 NULL。 (字符串长度可能不正确,但这不应该把整个事情搞砸。)

最佳答案

当您想通过函数参数返回指针时,您需要使用双重间接寻址:

int shorten(char *exp, int maxlength, char **exp_new)

更好的签名是

char* shorten(char *exp, int maxlength, int *length)

直接返回结果的地方。

编辑:当函数名称“shorten”描述其要执行的操作时,明显的结果应该是缩短的字符串。搜索函数产生的字符串长度可以忽略不计。可以更改该函数,以便长度参数可以接受 NULL 指针。在这种情况下,如果调用者不感兴趣,您可以省略长度结果。但这取决于环境。

关于c - 缩短 C 字符串以从第一次出现的内容中排除更多字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19926214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com