将字符串中的小写字母转换成大写字母

GitHub跳转原题关系图返回列表

整行读入后逐字符扫描,把小写字母减 32 转大写,其余字符(含空格、数字、已有大写)原样输出。

OJ: roj

题目 ID: 1138

难度:入门

标签:字符串python

创建: 2026-09-29 20:25

更新: 2026-10-05 03:07

题目描述

给定一个字符串(长度不超过 100,可能包含空格),把其中所有小写字母转成大写,其余字符原样保留。输入一行字符串,输出转换后的结果。样例输入:helloworld123Ha;样例输出:HELLOWORLD123HA。

思路

整行读入后逐字符扫描,遇到小写字母减 32 转大写,其余原样输出即可。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 20:27
# update_at: 2026-09-29 20:27

import sys


def solve() -> None:
    """读入一行字符串,把其中的小写字母转成大写后输出。"""
    data = iter(sys.stdin.buffer.read().splitlines())  # 按行保留空格/换行,再逐行消费
    line = next(data).decode()                         # 取唯一的一行输入
    print(line.upper())                                # str.upper 只作用于小写字母,数字、符号、大写字母不受影响


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-05 03:07
 * update_at: 2026-10-05 03:07
 */
#include <cstdio>
#include <cctype>

// 题目:将字符串中的小写字母转换成大写字母(行内空格与非字母字符原样保留)。
// 思路:整行读入后逐字符扫描,小写字母减 32 转大写,其余字符原样输出。

const int MAXN = 105; // 串长不超过 100,预留一位放 '\0'
char buf[MAXN];

int main() {
    // fgets 读整行,遇到换行停止,行内空格完整保留
    if (fgets(buf, sizeof(buf), stdin) == NULL) return 0;

    for (int i = 0; buf[i] != '\0'; ++i) {
        // 跳过 fgets 读到的行末换行,避免污染输出
        if (buf[i] == '\n') break;
        if (buf[i] >= 'a' && buf[i] <= 'z') buf[i] = buf[i] - 32; // 小写 -> 大写
        putchar(buf[i]);
    }
    putchar('\n');
    return 0;
}