簡體   English   中英

C#中如何將輸入字符串轉換為大寫

[英]How to convert an input string to uppercase in c#

string choice = String.ToUpper(Console.ReadLine());

我想輸入一個字符串並將其轉換為大寫。 但是,有一個錯誤指出:

無法從“字符串”轉換為 System.Globalization.CultureInfo'

當我將鼠標懸停在Console.ReadLine()上時出現。 為什么這不起作用,有什么修復方法? 還有另一種方法嗎?

String.ToUpper是一個實例方法,這意味着您必須在字符串“上”使用它:

string input = Console.ReadLine();
string choice = input.ToUpper();

否則,您將使用帶有CultureInfo對象的重載 由於String不可轉換為System.Globalization.CultureInfo ,因此您會收到編譯器錯誤。 但它無論如何都會產生誤導,你不能在沒有實例的情況下使用實例方法,所以這會產生另一個錯誤:

String.ToUpper(CultureInfo.CurrentCulture);  // what string you want upper-case??!

非靜態字段、方法或屬性“string.ToUpper(CultureInfo)”需要對象引用

只有當方法是static時,才可以在沒有類型實例的情況下使用它。

它不是這樣工作的。

string choice = Console.ReadLine().ToUpper();

ToUpper 方法屬於 String 類。 它采用 System.Globalization.CultureInfo 類型的參數。

你可以寫:

字符串選擇 = Console.ReadLine().ToUpper();

也許你可以試試這個:

static void Main(string[] args)
{
    string input = Console.ReadLine();

    string choice = Capitalize(input);
    Console.ReadKey();
}

string Capitalize(string word)
{
    int current = 0;
    string output = "";

    for(int i = 0; i < word.Length(); i++)
    {
        current = (int)word[i];
        current -= 32;
        output += (char)current;
    }

    return output;
}

我所做的:

我從用戶那里得到一個輸入。 假設它是一個小寫單詞。 我將其中的每個字符轉換為 int (我得到 ASCII 代碼),然后將其放入int current 例如'a' = 97(ASCII碼),'A'為65。所以'A'小於'a',ASCII碼為32。 對於“b”和“c”……這個算法也有效。 但要小心! 這只適用於英文字母! 然后我將current值(ASCII 值)減為 32。我將它轉換回字符並將其添加到string output中。 for循環之后

我希望它有所幫助。 :D

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM