【问题标题】:get the last word (uppercase)获取最后一个单词(大写)
【发布时间】: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


【解决方案1】:

您需要添加 ctype.h 库才能使用 toupper 函数。 我逐个字符地检查字符串是否是字母字符,这要归功于 ASCII 值,代码在这里:

#include <stdio.h>
#include <unistd.h>
#include <ctype.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)
    {
        if ((last_word[i] > 64 && last_word[i] <91) || (last_word[i]> 96 && last_word[i] < 123 ))
        printf("%c", toupper(last_word[i]));
        
        i++;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多