我需要关于 C 程序的帮助。我的任务是删除所有不是字母的字符并将单词的每个第一个字母更改为大写字母并返回已删除的非字母的数量,例如 {{1} } 到 "i love programming!"
,它应该 prop return "ILoveProgramming"
(已删除的非字母数)。我不能使用 3
, <ctype.h>
<stdlib.h> or
[]headers,
1only to declare array, and I can only use numbers
0and
int message_compression(char * txt );`)到目前为止,我设法更改了字母,但我不知道如何删除不是字母的字符。
. Also I can't change the function definition or do anything with that (
答案 0 :(得分:1)
如果允许您定义其他函数,例如 is_letter()
和 to_capital()
并在 message_compression()
的实现中使用它们,以下是简单解决方案的伪代码:
i = 0
读取索引,j = 0
写入索引i
处的字符不是字母:
i
处的字符是空终止符,则在偏移量 j 处设置一个空终止符并返回 i - j
i
to_capital
处存储字符i
(偏移量j
处的字符)i
和 j
i
处的字符是一个字母:
i
处的字符复制到偏移量j
i
和 j
尝试在为赋值施加的约束内用 C 语言编写代码。
这是一个简化的框架:
#include <stdio.h>
int is_letter(char c) {
// simple solution for ASCII
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
char to_capital(char c) {
// simple solution for ASCII
if (c >= 'a' && c <= 'z')
return 'A' + (c - 'a');
else
return c;
}
int message_compression(char* txt) {
int i = 0, j = 0;
for (;;) {
while (!is_letter(txt[i])) {
if (txt[i] == '\0') {
txt[j] = '\0';
return i - j;
} else {
i++;
}
}
txt[j++] = to_capital(txt[i++]);
while (is_letter(txt[i])) {
txt[j++] = txt[i++];
}
}
}
int main() {
char txt[1001];
puts("Text:");
if (fgets(txt, sizeof txt, stdin)) {
int deleted = message_compression(txt);
printf("After change: %s\n", txt);
printf("Characters removed: %d\n", deleted);
}
return 0;
}