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
CodePudding user response:
C#
string a = "hello WORLD";
string b = new string(a.Select(_ => char.IsLower(_) ? char.ToUpper(_) : char.ToLower(_)).ToArray());
CodePudding user response:
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.
CodePudding user response:
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));
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));