简体   繁体   中英

How to convert an input string to uppercase in c#

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?

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 .

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.

You can write:

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

Maybe you could try this:

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM