gpt4 book ai didi

c - 删除字符串的子字符串

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

所以我在 Talentbuddy 上做了一些编码练习(对于那些知道的人),我不明白为什么我不能完成这个练习。该练习是从字符串中删除子字符串,给出字符串输入,开始删除字符的位置 P 和需要删除的字符数 N。

这是我所做的:

#include <stdio.h>
#include <unistd.h>

void remove_substring(char *s, int p, int n)
{
int idx;

idx = -1;
while (s[++idx] != '\0')
write(1, &s[idx == p - 1 ? idx + n : idx], 1);
}

当输入为“abcdefghi”、P = 9 且 N = 1 时,给出的结果为“abcdefgh”,与我使用函数得到的结果完全相同。但 TalentBuddy 一直说我的输出是错误的,我不认为他(talentbuddy)错了。也许“h”和“\0”之间有空格或其他东西。但我无法理解它,因为当我在末尾添加另一个 write(1, "END", 3) 时,它看起来像“abcdefghEND”。

最佳答案

如果问题专门针对字符串( NULL 终止)为什么不能这么简单呢,除非是作业。

void removesubstr( const char *string, const char *substring )
{
char *p = strstr(string, substring);
if(p)
{
strcpy(p,p+strlen(substring));
}
}

关于c - 删除字符串的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25748743/

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