【问题标题】:Change every other alpha character in a string to uppercase using C使用 C 将字符串中的每个其他字母字符更改为大写
【发布时间】:2013-03-07 14:18:57
【问题描述】:

有人会用我编写的以下代码引导我朝着正确的方向前进吗?基本上我试图让字符串中的所有其他字符都以大写字母打印,同时不考虑空格或其他非字母字符。

示例:字符串输入 = "thanks for the add" 应打印为 "ThAnKs ForR tHe AdD"

int main (void) 
{
    char* input = GetString();
    if (input == NULL)
        return 1;
    for (int i = 0, x = strlen(input); i < x; i+=2)
        input [i] = toupper(input[i]);
    printf("%s\n", input);
    return 0;
}

注意:我是计算机科学的新手,目前正在通过 edx.org 学习 CS50x

【问题讨论】:

    标签: c for-loop toupper


    【解决方案1】:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        char st[] = "thanks for the add";
        for(int i=0; i<strlen(st); i++)
            st[i++]=toupper(st[i]);
        cout<<st<<endl;
    }
    

    【讨论】:

    • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
    【解决方案2】:

    只需使用isalpha 忽略其他类型的字符:

    #include <string.h>
    #include <stdio.h>
    #include <ctype.h>
    int main (void) 
    {
        char input[] = "thanks for the add";
        int  alpha_count = 0;
        for (int i = 0, x = strlen(input); i < x; i++) {
          if (isalpha(input[i])) {
            if (alpha_count++ % 2 == 0 ) 
              input [i] = toupper(input[i]);
          }   
        }   
        printf("%s\n", input);
        return 0;
    }
    

    【讨论】:

    • 为什么要调用isalpha?如果我没记错的话,toupper 函数仅在字符可以转换为大写时(即,如果它是字母字符)修改字符。否则,它保持不变。
    • 由于 OP 想要在 alpa 字符上的 uc/lc 之间交替,if 语句保护计数器。否则空格也会触发交替计数器。
    • 谢谢。我在这件事上花费的时间比我愿意承认的要多。模数的使用是我所缺少的。
    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2012-01-03
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多