What If I Want to Switch Case in C#?
You may be interested in whether all the characters (or just one) in a C# string are uppercase or lowercase characters. And you may need to convert from one to the other.
Distinguishing between all-uppercase and all-lowercase strings
You can use the
switch statement to look for a particular string. Normally, you use the
switch statement to compare a counting number to some set of possible values; however,
switch does work on
string objects as well. This version of the termination section in
BuildASentence uses the
This approach works because you’re comparing only a limited number of strings. The
for loop offers a much more flexible approach for searching for string values. Using the case-less
Compare() gives the program greater flexibility in understanding the user.
Converting a string to upper- or lowercase
Suppose you have a string in lowercase and need to convert it to uppercase. You can use the
string lowcase = "armadillo";
string upcase = lowcase.ToUpper(); // ARMADILLO.
Similarly, you can convert uppercase to lowercase with
What if you want to convert just the first character in a string to uppercase? The following rather convoluted code will do it:
string name = "chuck";
string properName =
char.ToUpper(name).ToString() + name.Substring(1, name.Length - 1);
The idea in this example is to extract the first
name), convert it to a one-character string with
ToString(), and then tack on the remainder of
name after removing the old lowercase first character with
You can tell whether a string is uppercased or lowercased by using this scary-looking
line, false) == 0) ... // True if line is all upper.
Compare() method is comparing an uppercase version of
line itself. There should be no difference if
line is already uppercase. The
CultureInfo.InvariantCulture property tells
Compare() to perform the comparison without considering culture. You can read more about it at Microsoft.com. If you want to ensure that the string contains all lowercase characters, stick a not (
!) operator in front of the
Compare() call. Alternatively, you can use a loop.