【发布时间】:2015-11-09 10:12:36
【问题描述】:
所以我正在尝试创建一个程序,该程序查看 main 中定义的字符串,并删除所有非字母字符(不包括 \0)。到目前为止,这是我的代码:
/* Write code to which considers the string currently saved
* in the 'name' array, removes all spaces and non-alphabetical
* chars from the string, and makes all alphabetical characters
* lower case. */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define NAMELEN 30
int main (void) {
char name[NAMELEN];
strcpy(name, " William B. Gates");
int i, length, check;
length = strlen(name);
for ( i = 0; i < length; i++ ) {
check = isalpha(name[i]);
if ( check == 0 ) {
for ( ; i < length; i++ ) {
name[i] = name[i+1];
}
}
}
printf("The length is %lu.\n", strlen(name));
printf("Name after compression: %s\n", name);
return EXIT_SUCCESS;
}
所以对于测试数据“William B. Gates”,输出应该是“WilliamBGates”,不幸的是我得到的输出是:
The length is 16.
Name after compression: William B. Gates
我认为威廉前面的空格已被删除,但我无法确定。 感谢您的帮助!
【问题讨论】:
-
@user3121023 改成
length = strlen(name); for ( i = 0; i < length; i++ ) { check = isalpha(name[i]); if ( check == 0 ) { for ( j = i ; j < length; j++ ) { name[j] = name[j+1]; } } }得到输出WilliamB Gates为什么不删除第二个空格? -
你根本不需要双循环。您需要一个源和目标指针,以及对字符串的一次遍历。
-
@WhozCraig 我该怎么做呢。我是一个非常基础的程序员,我只是为了考试练习而做这些问题,而不是出于需要或乐趣......有什么建议吗?
-
@user3121023 你认为我应该使用
isspace()添加一个单独的for循环来检查新字符串中的空格吗? -
如果您更喜欢使用索引下标而不是指针,那么对于 Vlad 的回答也是如此。