gpt4 book ai didi

c - 玩转字符串函数

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

这是一个非常小的问题,而且可能是非常愚蠢的问题!但是为什么我在这个应该删除双字母的函数的输出中返回垃圾?

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

char *makehello( char *s ) {
char new[16] ;
int i ;
int c = strlen(s);
for ( i = 0; i < (c + 1); i++)
if (toupper(s[i]) != toupper(s[i+1]))
new[i] = toupper(s[i]);
return strdup( new ) ;
}

int main(void) {
char *new;
char data[100];
scanf("%s", data);
new = makehello(data);
printf("%s", new);
return 0;
}

最佳答案

您需要为"new"数组单独计数。您将它们存储在索引“i”(您找到该字符的位置)处,但您真正想要的是从位置 0 开始存储它们并增加此计数。

编辑:当然这不是一个完全可靠的方法。

即类似这样的内容:

   for ( i = 0; i < c; i++)
{
if (toupper(s[i]) != toupper(s[i+1]))
{
new[count++]= toupper(s[i]);
}
}
new[count] = '\0';

关于c - 玩转字符串函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8260287/

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