简体   繁体   中英

Make lower case upper and upper case lower in a string

I have been struggling on using .ToUpper and .ToLower to convert words in strings to the opposite case.

Example 1:

Input: hello WORLD
Output: HELLO world

Example 2:

Input: THIS is A TEST
Output: this IS a test

C#

string a = "hello WORLD";

string b = new string(a.Select(_ => char.IsLower(_) ? char.ToUpper(_) : char.ToLower(_)).ToArray());

Define a function that converts a single-cased word to the opposite case:

string ConvertCase(string word)
{
    if (word.All(char.IsUpper)) return word.ToLower();
    if (word.All(char.IsLower)) return word.ToUpper();
    return word;
}

Then split your sentence into words, convert each word and join back into a string:

var convertedSenetence = string.Join(' ', sentence.Split(' ').Select(ConvertCase));

Working example


Of course this can be inlined if you prefer:

var convertedSenetence = string.Join(' ', sentence
    .Split(' ')
    .Select(word =>
        word.All(char.IsUpper) ? word.ToLower() :
        word.All(char.IsLower) ? word.ToUpper() :
        word));

You could do something like this:

string input = "hello WORLD";
string output = "";
foreach(char c in input ){
    output += Char.IsUpper(c) ? Char.ToLower(c) : Char.ToUpper(c);
}
Console.WriteLine(output);

The code above inverts the case of every char in the string, so doesn't matter if its camelCase, PascalCase or just upper/lower case.

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