从字符串中删除所有非字母字符并将单词的每个第一个字母更改为大写字母

时间:2021-01-17 15:42:27

标签: c string pointers

我需要关于 C 程序的帮助。我的任务是删除所有不是字母的字符并将单词的每个第一个字母更改为大写字母并返回已删除的非字母的数量,例如 {{1} } 到 "i love programming!",它应该 prop return "ILoveProgramming" (已删除的非字母数)。我不能使用 3, <ctype.h><stdlib.h> or []headers,1only to declare array, and I can only use numbers0andint message_compression(char * txt );`)到目前为止,我设法更改了字母,但我不知道如何删除不是字母的字符。

. Also I can't change the function definition or do anything with that (

1 个答案:

答案 0 :(得分:1)

如果允许您定义其他函数,例如 is_letter()to_capital() 并在 message_compression() 的实现中使用它们,以下是简单解决方案的伪代码:

  • i = 0读取索引,j = 0写入索引
  • 重复:
    • 重复,而偏移量 i 处的字符不是字母:
      • 如果偏移量 i 处的字符是空终止符,则在偏移量 j 处设置一个空终止符并返回 i - j
      • 否则增加i
    • 在偏移量to_capital处存储字符i(偏移量j处的字符)
    • 递增 ij
    • 重复,而偏移量 i 处的字符是一个字母:
      • 将偏移量i处的字符复制到偏移量j
      • 递增 ij

尝试在为赋值施加的约束内用 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;
}