【发布时间】:2021-04-29 23:20:24
【问题描述】:
我正在编写一个代码,以大写形式打印字符串中的最后一个单词并删除特殊字符或数字(如果有),我的代码现在只打印最后一个单词如何将其变为大写并删除任何特殊字符
#include <stdio.h>
#include <unistd.h>
int main()
{
char line[80] = "abc dfg, egh.";
int i = 0, j;
char *last_word;
while (line[i] != '\0')
{
if (line[i] <= 32 && line[i + 1] > 32)
last_word = &line[i + 1];
i++;
}
i = 0;
while (last_word && last_word[i] > 32)
{
write(1, &last_word[i], 1);
i++;
}
}
【问题讨论】:
-
使用
toupper -
将其复制到一个新数组中,跳过任何“特殊”字符,并使用
toupper作为您实际复制的字符。 -
另外几个注意事项,请尽量避免magic numbers,使用the standard character classification functions。
-
Loot at
strrchr()以查找字符串中的最后一个空格(或仅使用 strrchr() 和'\0'查找结尾并向后查找最后一个单词)。您可以使用isalpha()仅检查[A-Za-z]。
标签: c algorithm data-structures