Fundamentals of Characters

Introduction

To recognize the symbols (letters, digits, special characters, etc) used in an application, the C# language provides a data type named char. The char data type is identified in the .NET Framework by a structure named Char. This structure is represented by a 16-bit value.

To declare a variable that can hold one character, a letter, or a symbol, use the char data type or the Char structure. To initialize the variable, include its value between two single-quotes. Here are examples:

char gender = 'm';
char moneySymbol = '$';
char multiplication = '*';
char numberOne = '1';

You can also use the var or the dynamic keyword if you are initializing the variable.

Passing a Character to a Function or Method

Like a normal value, a character can be passed to a function or method as argument. Here is an example:

public string EmploymentStatus;

void GetEmploymentStatus(char s)
{
    switch (s)
    {
        case 'p':
            EmploymentStatus = "Part-Time";
            break;
        case 'f':
            EmploymentStatus = "Full-Time";
            break;
        case 'c':
            EmploymentStatus = "Contractor";
            break;
        default:
            EmploymentStatus = "Unknown";
            break;
    }
}

When calling the function or method, pass a value for the argument in single-quotes. Here is an example:

using static System.Console;

string result = GetEmploymentStatus('f');

WriteLine("Employment Status: {0}", result);

WriteLine("===============================");

string GetEmploymentStatus(char s)
{
    string employmentStatus;

    switch (s)
    {
        case 'p':
            employmentStatus = "Part-Time";
            break;
        case 'f':
            employmentStatus = "Full-Time";
            break;
        case 'c':
            employmentStatus = "Contractor";
            break;
        default:
            employmentStatus = "Unknown";
            break;
    }

    return employmentStatus;
}

This would produce:

Employment Status: Full-Time
===============================
Press any key to continue . . .

Returning a Character From a Method

You can create a function or method that returns a character. To do this, when creating the method, on the left of its name, specify the return type as char. In the body of the method, before the closing curly bracket. return a character. Here is an example:

public class Employee
{
    public char SetEmploymentStatus()
    {
        char s = 's';
        return s;
    }
}

When calling the method, you can assign its return value in a character.

Case Conversions for Characters

Converting a Character to Lowercase

To let you convert a character to lowercase, the Char structure is equipped with the ToLower() method. It is overloaded with two versions. One of the versions uses the following syntax:

public static char ToLower(char c)

This method follows the same logic as its ToUpper() counterpart. If the character is not an alphabetic character, it would be kept "as-is". If the character is an uppercase alphabetic character, it would be converted to lowercase. If it is in lowercase, it would not be converted.

Converting a Character to Uppercase

The English language uses two character representations: lowercase and uppercase. The characters in lowercase are: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z. The equivalent characters in uppercase are represented as A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Characters used for counting are called numeric characters; each one of them is called a digit. They are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. There are other characters used to represent things in computer applications, mathematics, and others. Some of these characters, also called symbols are ~ , ! @ # $ % ^ & * ( ) _ + { } ` | = [ ] \ : " ; ' < > ? , . / These characters are used for various reasons and under different circumstances. For example, some of them are used as operators in mathematics or in computer programming. Regardless of whether a character is easily identifiable or not, all these symbols are character types and can be declared using the char data type followed by a name.

An alphabetic character, for any reason judged necessary, can be converted from one case to another. The other characters, non-alphabetic symbols, and the numbers, do not have a case and therefore cannot be converted in cases.

To let you convert a character from lowercase to uppercase, the Char structure is equipped with a method named ToUpper(). It is overloaded with two versions. One of the versions of this method uses the following syntax:

public static char ToUpper(char c)

This method takes a character as argument. If the character is already in uppercase, it would not change. If the character is a lowercase alphabetic character, it would be converted to uppercase. If the character is not an alphabetic character, it would be kept "as-is".

The Characters of a String

Escape Sequences

An escape sequence is a type of character, usually non-readable, that the compiler must use for some operation, such as using a particular way to display a string. The available escape sequences are:

Escape Sequence Name Description
\a Bell (alert) Makes a sound from the computer
\b Backspace Takes the cursor back
\t Horizontal Tab Takes the cursor to the next tab stop
\n New line Takes the cursor to the beginning of the next line
\v Vertical Tab Performs a vertical tab
\f Form feed  
\r Carriage return Causes a carriage return
\" Double Quote Displays a quotation mark (")
\' Apostrophe Displays an apostrophe (')
\? Question mark Displays a question mark
\\ Backslash Displays a backslash (\)
\0 Null Displays a null character

To use an escape sequence, you can also first declare a char variable and initialize it with the desired escape sequence in single-quotes.

A String as an Array of Characters

To support strings, the .NET Framework provides a class named String. This class is defined in the C# language as the string data type. Here is an example of declaring, initializing, and using a string object:

string gender = "Female";

A string is a group, or an array, of characters. After declaring and initializing a string, it is considered an array of values where each character occupies a specific position. The positions are numbered so that the most left character of the string occupies index 0; the second character is at index 1, and so on.

To support this idea of an array of characters, the String class is equipped with a numbered (called indexed) property named Chars. This is also how you can retrieve the character at a specific index in the string, using the [] operator of arrays. Here is an example:

var gender = "Female";
var gdr = gender[2];

You can access the Length property to know the number of characters in a string.

Once (and because) a string is considered a collection of items, you can use the foreach operator to access each member of the collection. Here is an example:

using static System.Console;

string gender = "Female";

WriteLine("Gender: {0}", gender);
WriteLine("-------------------------------");

WriteLine("Individual Characters");

foreach(char c in gender)
    WriteLine("Character: {0}", c);

WriteLine("===============================");

This would produce:

Gender: Female
-------------------------------
Individual Characters
Character: F
Character: e
Character: m
Character: a
Character: l
Character: e
===============================
Press any key to continue . . .

Categories of Characters

As far as computers or operating systems are concerned, every readable or non-readable symbol used in an application is a character. All those symbols are considered objects of type char. The Char structure can recognize every one of them. In fact, the Char structure makes the symbols into various categories.

An alphabetical letter is a readable character recognized by a human language. To let you find out whether a character is a letter, the Char structure is equipped with a static method named IsLetter. It is overloaded with two versions. A digit is a symbol used in a number. It can be 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. To let you find out whether a character is a digit, the Char structure is equipped with the IsDigit() static method that is overloaded with two versions. In the same way, the Char structure provides various methods to test the category of characters being used. All these methods are static and they are given in two versions. Each has a version that takes one argument as a character. If the argument is the type sought, the method returns true. Otherwise it returns false. The methods are:

Method Returns true if the argument is
IsLetter(char c) A letter
IsLower(char c) A lowercase letter
IsUpper(char c) An uppercase letter
IsDigit(char c) A digit
IsNumber(char c) A digit or any other type of number
IsLetterOrDigit(char c) A letter or a digit
IsControl(char c) A control character (Ctrl, Shift, Enter, Del, Ins, etc)
IsPunctuation(char c) A punctuation such as , . - ! ? ' " ( ) | # \ / % & * > @ < » «
IsSymbol(char c) A symbol such as | + ¢ ¤ ± £ = ^ ¨ $
IsWhiteSpace(char c) An empty space such as created by pressing the SPACE bar
IsSeparator(char c) An empty space or the end of a line

Here are examples of calling these methods:

using static System.Console;

WriteLine("===============================");
WriteLine("Proposition  Conclusion");
WriteLine("-------------------------------");
WriteLine("q is a Letter {0}", Char.IsLetter('q'));
WriteLine("-------------------------------");
WriteLine("a is a lowercase letter {0}", Char.IsLower('a'));
WriteLine("-------------------------------");
WriteLine("W is an uppercase letter {0}", Char.IsUpper('W'));
WriteLine("-------------------------------");
WriteLine("1 is a digit {0}", Char.IsDigit('1'));
WriteLine("-------------------------------");
WriteLine("w is a letter or a digit {0}", Char.IsLetterOrDigit('w'));
WriteLine("-------------------------------");
WriteLine("3 is a letter or a digit {0}", Char.IsLetterOrDigit('w'));
WriteLine("-------------------------------");
WriteLine("0 is a number {0}", Char.IsNumber('0'));
WriteLine("-------------------------------");
WriteLine("_ is a punctuation mark {0}", Char.IsPunctuation('_'));
WriteLine("-------------------------------");
WriteLine("# is a punctuation mark{0}", Char.IsPunctuation('#'));
WriteLine("-------------------------------");
WriteLine("\\ is a punctuation mark {0}", Char.IsPunctuation('\\'));
WriteLine("-------------------------------");
WriteLine(" is a white space {0}", Char.IsWhiteSpace(' '));
WriteLine("-------------------------------");
WriteLine(" is a separator {0}", Char.IsSeparator(' '));
WriteLine("-------------------------------");
WriteLine(" + is a symbol {0}", Char.IsSymbol('+'));
WriteLine("===============================");

This would produce:

===============================
Proposition  Conclusion
-------------------------------
q is a Letter True
-------------------------------
a is a lowercase letter True
-------------------------------
W is an uppercase letter True
-------------------------------
1 is a digit True
-------------------------------
w is a letter or a digit True
-------------------------------
3 is a letter or a digit True
-------------------------------
0 is a number True
-------------------------------
_ is a punctuation mark True
-------------------------------
# is a punctuation markTrue
-------------------------------
\ is a punctuation mark True
-------------------------------
 is a white space True
-------------------------------
 is a separator True
-------------------------------
 + is a symbol True
===============================
Press any key to continue . . .

You can apply a conditional statement to a method to find out what character is at a certain position.


Previous Copyright © 2001-2023, FunctionX Friday 26 November 2021 Next