Codeforces 281A 單字大寫化 – 翻譯與解答

難易度 : 800

英文原文如下

Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.

Note, that during capitalization all the letters except the first one remains unchanged.

中文翻譯

大寫化是將單字的第一個字母寫成大寫。您的任務是將給予的單字進行大寫化。

請注意,在大寫化期間,除第一個字母外,所有字母保持不變。

輸入

A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103.

一行包含了非空白的單字,單字由小寫及大寫的英文字母組成,長度不會超過 103

輸出

Output the given word after capitalization.

印出大寫化後的給予單字

範例

輸入ApPLe
輸出ApPLe
輸入konjac
輸出Konjac

解題思路

在這一題當中,直接針對第一個字母轉成大寫應該會比判斷其是大小寫再轉換來的快速 (題目有說非空白,所以至少有一個字母)

另外,也要注意若僅有一位字母的話,是沒辦法使用split等內建函式的,故需要做特別的判斷才可以。

C#解決方案

方案1

string inStr = Console.ReadLine();

if(inStr.Length == 1){
    Console.WriteLine(inStr.ToUpper());
}
else {
    Console.WriteLine(char.ToUpper(inStr[0]) + inStr.Substring(1));
}

Java解決方案

方案1

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String inStr = scanner.nextLine();
        
        if(inStr.length() == 1){
            System.out.println(inStr.toUpperCase());
        }
        else {
            System.out.println(Character.toUpperCase(inStr.charAt(0)) + inStr.substring(1));
        }
    }
}

Python3解決方案

方案1

inStr = input()

if(len(inStr)==1):
    print(inStr.upper())
else:
    print(inStr[0].upper()+inStr[1:])

結論

有點忙的一天,先寫個大概之後再補充說明 (金拍謝)

這一題當中,會用到比較多內建的函式,不管是排序還是轉型,甚至是最後將陣列組回字串的 join之類的用法 (當然也可以土法煉鋼的用 for 迴圈啦哈哈,不過那樣看起來有點遜…)

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Problem – 281A – Codeforces

一些其他的文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *