codeasy .net
or Sign Up

Lection in the Big Kitchen

The final task of the morning session completed and lunch having been eaten, we settled in for the second part of Ritchie's lesson about new types. "We'll take it easy this afternoon," Ritchie said, "and teach you about one more type today."

He continued, "The name of this type is char. It represents one character: a letter, a digit, or any other symbol that you can imagine. To represent a char value in C#, you must enclose it in single quotes: 's'. Here is an example of how to create a char variable." And with that, Ritchie returned to the whiteboard.

char someLetter = 'a';
char someSymbol = '?';
char anotherOne = '+';

You can read a char from the console using the method char.Parse(...), the same as you did with double and int:

string input = Console.ReadLine();
char inputSymbol = char.Parse(input);

To output a char variable to the console, you can use the Console.WriteLine(...) method, the same, again, as with the other types we know. For example:

char someChar = 'h';
Console.WriteLine(someChar); // Outputs: h
Console.WriteLine('h'); // Outputs: h
Console.WriteLine('#'); // Outputs: #

Write a program that reads one char from the console and then outputs it back to the console.

"Ritchie," someone called, "isn't a char just a piece of a string?"

"Well..." he began, "You could say that a char can be a part of the string. As you all know, strings consist of characters. In C#, you can get a char by requesting the data from one place in the string. Consider a string: "Resistance". You can get the first character 'R' out of the string by appending [0] at the end of the string like this: "Resistance"[0]. You can get the second character out of the string by appending [1] at the end of the string: "Resistance"[1]. You may see a pattern here - finally, you can get the nth character of the string by appending [n-1] at the end of the string: "Resistance"[n-1]. Like this:"

char firstCharacter = "Resistance"[0];
char secondCharacter = "Resistance"[1];
char thirdCharacter = "Resistance"[2];
char oneBeforeLastCharacter = "Resistance"[8];

Console.WriteLine(firstCharacter);          // Outputs: R
Console.WriteLine(secondCharacter);         // Outputs: e
Console.WriteLine(thirdCharacter);          // Outputs: s
Console.WriteLine(oneBeforeLastCharacter);  // Outputs: c

This opens up some unique capabilities. You can use an int variable as an index in the brackets [] with the string variable as well:

string resistance = "Resistance";
char firstCharacter = resistance[0];
char oneBeforeLastCharacter = resistance[8];

Console.WriteLine(firstCharacter);          // Outputs: R
Console.WriteLine(oneBeforeLastCharacter);  // Outputs: c
Console.WriteLine(resistance[8]);           // Outputs: c
Console.WriteLine(resistance[3]);           // Outputs: i

int index = 3;
Console.WriteLine(resistance[index]);       // Outputs: i

Write a program that reads one string from the console and then outputs the second character of that string to the console. For example:
>Make deals with machines
a

C# programmer time

Write a program that reads a string and an integer number N from the console. It should then output the string's Nth character to the console. For example:
>Make deals with machines
>4
e

You can also perform other functions on a char, such as checking whether it's an uppercase letter, a lowercase letter, a digit, etc. Here is a full list of char functions. Here are the ones most widely used:

  1. char.IsDigit(someChar) - checks whether someChar is a decimal digit. Returns a bool value.
  2. char.IsLetter(someChar) - checks whether someChar is a letter. Returns a bool value.
  3. char.IsLower(someChar) - checks whether someChar is a lowercase letter. Returns a bool value.
  4. char.IsUpper(someChar) - checks whether someChar is an uppercase letter. Returns a bool value.
char someChar = 'A';
if (char.IsDigit(someChar))
{
    Console.WriteLine($"{someChar} is a digit");
}
else
{
    Console.WriteLine($"{someChar} is NOT a digit");
}

if (char.IsLetter(someChar))
{
    if (char.IsUpper(someChar))
    {
        Console.WriteLine($"{someChar} is an uppercase letter");
    }
    else
    {
        Console.WriteLine($"{someChar} is a lowercase case letter");
    }
}
else
{
    Console.WriteLine($"{someChar} is NOT a letter");
}

// Outputs:
// A is NOT a digit
// A is an uppercase letter

Write a program that reads 5 chars from the console and then outputs to the console only the uppercase letters, in the same order in which they were entered. Example:
>D
>4
>?
>S
>a
D
S

Ritchie put down the marker and erased the whiteboard. "Now, hold on to your seats for this next statement." He continued, speaking slowly and purposefully, "A char is represented as a number in the computer memory."

You could hear a pin drop as we tried to decipher this. Someone in the back asked the question we were all thinking: "You just said that a char is a character. How can it be a number?"

It sounds complicated, I know. But a char is really represented by a number. String variables are also represented by numbers. You have to remember - a computer processor can only decipher numbers. It doesn't understand characters and strings. They were created to make our lives easier. When you write the following,

char someChar = 'a';

This is what happens in the memory:

C# Char Type explanation

"Do we need to know how the char is stored Ritchie?" asked someone from the crowd.
"You do, at least to know how to use Console.Read()."
"You mean Console.ReadLine()?"
"No, I meant Console.Read(). While similar, this method reads only one char from the console and returns it to you, rather than a string like Console.ReadLine() does. Here is an example:"

int charCode = Console.Read();

You probably noticed that in the code above, Console.Read() returns an int, not a char. This int represents the number that is really stored in the memory for that char. For example, 'a' is stored as 97; 'A' as 65; and 'μ' as 181. In C#, the correspondence between the real character and its numerical representation is made by the Unicode industry standard. Basically, it binds characters to numbers. You can easily find in the network the list of Unicode characters.

To convert an integer char representation, say 97, to a real character like 'a', you can use the Convert.ToChar(charCode) method:

int charCode = Console.Read(); // Reads Unicode representation of the char
char theRealChar = Convert.ToChar(charCode); // Converts Unicode code of the
                                             // char to a char type

The code above waits for the user to input a character (it even can be several characters) and press Enter. The program then reads the Unicode code of the character and converts it to a char type. Try it yourself!

Write a program that reads from the console one char using Console.Read() and Convert.ToChar(...) methods. After this, the program should output "Digit" "Letter" or "Not a digit and not a letter" to the screen, depending on what the character is.

There is also the method Console.Write(...). It writes whatever you give to it to the screen, but does not switch to a new line after each write like Console.WriteLine(...) does. You can use Console.Write(...) with strings, ints, chars, etc. the same as you did with Console.WriteLine(...). Here are some examples:

char two = '2';
char a = 'a';
char b = 'b';
Console.Write(two);
Console.Write(a);
Console.Write(b);

// Outputs: 2ab
int two = 2;
int ten = 10;
int five = 5;
Console.Write(two);
Console.Write(ten);
Console.Write(five);

// Outputs: 2105
char two = '2';
int ten = 10;
int five = 5;
Console.Write(two);
Console.Write(ten);
Console.WriteLine(five);

// Outputs: 2105
char two = '2';
int ten = 10;
int five = 5;
Console.Write(two);
Console.Write(ten);
Console.WriteLine(five);
Console.Write(five);

// Outputs: 2105
// 5
Console.Write("Hello, ");
Console.Write("Teo!");

// Outputs: Hello, Teo!

Write a program that reads 2 characters from the console and outputs them on one line. You can use either the Console.Read() or Console.ReadLine() methods. For example:
>K
>2
K2

Write a program that reads an integer count, for the number of characters to read, from the console. Then, from a new line, the program should read count characters written in one line from the console. Finally, the program should output only the letters from the characters to the console on one line. For example:
>10
>FL45H0b12c
FLHbc

C# programmer life

After working through all of these examples, some people were beginning to pack up and leave the kitchen. A whole day of learning had gone by, and we had a whole new set of types to use in our code! Before anyone had reached the doors, Ritchie shouted one more lesson over the noise.

"Before you go, I want to add that you can compare chars using '>' and '<'. The comparison is done in alphabetical order: 'a' is less than 'b'; and these comparisons are case-sensitive, which means that you should only compare uppercase letters with uppercase letters and lowercase letters with lowercase ones. Here are a couple of examples."

if ('a' < 'b')
{
    Console.WriteLine("True!");
}

if ('M' > 'Z')
{
    Console.WriteLine("False!");
}

// Outputs: True!

This site uses cookies. By continuing to browse this site you are agreeing to our use of cookies.

Got it!