玩转字符串函数
这是一个非常小的问题,而且可能是非常愚蠢的问题!但是为什么我在这个应该删除双字母的函数的输出中返回垃圾?
#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;
}
This is a very small question, and probably something really silly! But why am I getting garbage returned in my output for this function which should remove double letters?
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要为“新”数组单独计数。您将它们存储在索引“i”(您找到该字符的位置)处,但您真正想要的是从位置 0 存储它们并增加此计数。
编辑:当然这不是一个完全可靠的方法。
即像这样:
You need a separate count for your 'new' array. You're storing them at index 'i' (where you found the character), but what you really want is to store them from position 0 and increment this count instead.
EDIT: Of course this isn't a fullproof method.
i.e something like this:
该行
应该是
然后您需要在
strdup
new[i]=0; 之前大括号也不会顺利。
编辑
忘记需要更改以下内容
并在 for 循环中
和 for 循环之后
The line
should be
And you then need before the
strdup
new[i]=0;Braces would not go amise either.
EDIT
Forgot need to change the following
and in the for loop
and after the for loop
这是该算法的一个相当紧凑的 C99 版本(省略了标头,示例):(
此版本区分大小写。)
Here's a reasonably compact C99 version of the algorithm (headers omitted, example):
(This one discriminates case.)