gpt4 book ai didi

c - 替换 C 中的字符

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:50 26 4
gpt4 key购买 nike

这是 lab assignment 的一部分

我必须实现以下功能...

void replaceChar(char s[], char c,int len)

Description: Replace every character of s with c. len indicates the length of s.

我将其提交给我的类(class)使用的自动评分器,它告诉我“替换字符串的长度不同。”我对此进行了广泛测试,没有发现任何问题。这是我的完整功能:

void replaceChar(char s[], char c, int len) {
printf("\n");
for (int i = 0; i < len; i++) {
s[i] = c;
printf("%c",s[i]);
}
}

我很感激你能给我的任何帮助!

以下是我的一些测试用例:

char s1[5] = {'h','e','l','l','o'};

char s3[10] = {'h','e','l','l','o',' ','h','i','i','i'};
char rep1 = 'x';
replaceChar(s1,rep1,5);
replaceChar(s3,rep1,10);

最佳答案

参见 my comment :

have you tried explicitly marking the NUL terminator? s[len] = '\0';

虽然这解决了问题,但我仍然会联系您的教授并询问他们为什么首先需要这样做。实验室未指定字符串 s 需要以 NUL 结尾。

顺便说一句(最初在 another of my comments 中提到),您应该在初始化 s1s3 时利用字符串文字,即

char s1[] = "hello";
char s3[] = "hello hiii";

这不仅看起来更简洁(并且避免了明确提及数组长度的需要),而且还保证了字符串也以 NUL 结尾。

关于c - 替换 C 中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342382/

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