How to convert an input string to uppercase in c#

2019-08-29 12:44发布

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

I want to input a string and convert it to upper case. However, there's an error that states :

cannot convert from 'string' to System.Globalization.CultureInfo'

that appears when I hover over the Console.ReadLine(). Why doesn't this work , and what fixes are there? And is there another way to do this ?

4条回答
Deceive 欺骗
2楼-- · 2019-08-29 12:56

It does not works this way.

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

The ToUpper method belongs to String class. It takes a parameter of type System.Globalization.CultureInfo.

查看更多
神经病院院长
3楼-- · 2019-08-29 13:06

You can write :

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

查看更多
来,给爷笑一个
4楼-- · 2019-08-29 13:13

String.ToUpper is an instance method, that means you have to use it "on" your string:

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

Otherwise you are using the overload that takes a CultureInfo object. Since String is not convertible to System.Globalization.CultureInfo you get the compiler error. But it's misleading anyway, you can't use an instance method without instance, so this yields another error:

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

An object reference is required for the non-static field, method, or property 'string.ToUpper(CultureInfo)

A method can be used without an instance of the type only if it is static.

查看更多
Lonely孤独者°
5楼-- · 2019-08-29 13:13

Maybe you can try this:

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

    Console.WriteLine(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;
}

What I do:

I get an input from the user. Let's suppose it is a lowercase word. I convert each characters in it to int (I get the ASCII code) and I put it into int current. For example 'a' = 97 (in ASCII code), and 'A' is 65. So 'A' is smaller than 'a' with 32 in ASCII code. For 'b' and 'c'... this algorithm also works. But beware! This only works for english letters! And then I decrease current (the ASCII value) with 32. I convert it back to a character and add it to string output. After the for loop

I hope it helps. :D

查看更多
登录 后发表回答