Case swapping
Description:
Given a string, swap the case for each of the letters.
e.g. CodEwArs --> cODeWaRS
Examples
Kata.Swap("") == ""
Kata.Swap("CodeWars") == "cODEwARS"
Kata.Swap("abc") == "ABC"
Kata.Swap("ABC") == "abc"
Kata.Swap("123235") == "123235"
using System; using System.Linq; public static class Kata { public static string Swap(string str) { return string.Join(string.Empty, str.Select(character => char.IsLower(character) ? char.ToUpper(character) : char.IsUpper(character) ? char.ToLower(character) : character)); } //public static string Swap(string str) //{ // str = string.Join(string.Empty, str.Select(Selector)); // return str; //your code here //} //public static char Selector(char character) //{ // char tempCharacter = character; // if (char.IsLower(character)) // { // tempCharacter = char.ToUpper(character); // } // else if (char.IsUpper(character)) // { // tempCharacter = char.ToLower(character); // } // return tempCharacter; //} }
其他人的解法
需要学习的是:char.ToUpper以及char.ToLower本身可以处理非大小写的字符,不需要另外多一个判断
using System; using System.Linq; public static class Kata { public static string Swap(string str) { return String.Concat(str.Select(c => Char.IsUpper(c) ? Char.ToLower(c) : Char.ToUpper(c))); } }
时间: 2024-10-14 02:11:45