c - 使用 C 将小写字母转换为大写字母

标签 c arrays string

问题陈述

我遇到一道编程竞赛题,题目如下:

You are given T name(s) in english letters. Each name will include some of the uppercase letters from A to Z, some of the lowercase letters from a to z and some spaces. You have to transform the name(s) from lowercase to uppercase. Letters that are originally uppercase will remain the same and the spaces will also remain in their places.


示例输入输出

如果我输入...

5
Hasnain Heickal    Jami
Mir Wasi Ahmed
Tarif Ezaz
     Mahmud Ridwan
Md    Mahbubul Hasan

计算机应该输出这个……

Case 1: HASNAIN HEICKAL    JAMI
Case 2: MIR WASI AHMED
Case 3: TARIF EZAZ
Case 4:      MAHMUD RIDWAN
Case 5: MD    MAHBUBUL HASAN
  • 请注意,分号和姓名的首字母之间需要恰好一个空格。

我的编码

这是我用 C 编写的代码:

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

int main(void)
{
    int T, i;
    char string [100];
    scanf("%d", &T);

    for (i=0; i<T; i++) 
    {
        gets(string);
        printf("Case %d: ", i);

        while (string[i])
        {
            putchar (toupper(string[i]));
            i++;
        }          

        printf("\n");
     }  

    getch();
    return 0;
}

现在,此代码无法生成所需的输出。我哪里做错了?我的语法有问题吗?有人可以指导我吗?请记住,我是一名中学生,只是 C 语言的初学者。

最佳答案

您需要一个接一个地循环遍历字符串中的每个字母。

在下面的这段代码中,我使用变量 K 完成了该操作,它从 0 到字符串的长度。

变量 I 跟踪字符串的数量。

int main(void)
{
  int T, i, k;
  char string [100];

  scanf("%d", &T);

  for ( i = 0; i < T; ++i)
  {
     gets (string);

     for(k=0; k<strlen(string); ++k)
     {
         putchar (toupper(string[k]));
     }
  }  

  getch();
  return 0;
}

回答您的问题:IDEOne Link

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
  int T, i,k;
  char string [100];

  scanf("%d ", &T);

  for ( i = 0; i < T; ++i)
  {
     gets (string);
     printf("[%d] : %s\n", i, string);

     for(k=0; k<strlen(string); ++k)
     {
         putchar (toupper(string[k]));
     }
     putchar('\n');
  }  

  return 0;
}

关于c - 使用 C 将小写字母转换为大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922076/

相关文章:

c++ - 为什么全局变量会给函数调用中的编译器优化带来麻烦?

c - cublas函数调用cublasSgemv

c - 指针是否在线程之间共享?

javascript - 提醒数组内的数据细节

c - ‘unary *’ 的类型参数无效(有 ‘int’ )

c - 如何使用双指针作为指针数组?

c - C 中的 char* 数组

c - 我的程序不接受使用 getchar 的 c 中的简单字符串

javascript - 如何在 JavaScript 中的类名语法中连接字符串?

r - 如何使用正则表达式提取 R 中字符串的不匹配部分?