Introduction to Characters
Introduction to Characters
Fundamentals of Characters
Introduction
To recognize the symbols used on a form (letters, digits, special characters, etc), 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:
using System; public class Exercise { static void Main(string[] args) { 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.
Practical Learning: Introducing Characters
Control | (Name) | Text |
GroupBox | Account Setup | |
Label | First Name: | |
TextBox | txtFirstName | |
Label | Middle Name: | |
TextBox | txtMiddleName | |
Label | Last Name: | |
TextBox | txtLastName | |
Label | ________________ | |
Label | New Password: | |
TextBox | txtNewPassword | |
Label | Confirm Password: | |
TextBox | txtConfirmPassword | |
GroupBox | Password Summary | |
Label | Number of Characters: | |
TextBox | txtCharacters | |
Label | Lowercase Letters: | |
TextBox | txtLowercaseLetters | |
Label | Uppercase Letters: | |
TextBox | txtUppercaseLetters | |
Label | Digits: | |
TextBox | txtDigits | |
Label | Symbols: | |
TextBox | txtSymbols |
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; public class Exercise { static 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; } public static int Main(string[] args) { string result = GetEmploymentStatus('f'); WriteLine("Employment Status: {0}", result); WriteLine("==============================="); return 5_264_140; } }
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".
Introduction to Strings
Fundamentals of Strings
As we have seen so far, a string is one or a group of characters. Based on this, to get a string, you can create a group of characters and include them in double-quotes.
To support strings, the .NET Framework provides a class named String. This class is defined in C# language as the string data type. Therefore, to create a string, you can declare a variable of type string or String. You can also use the dynamic keyword to declare the variable. Here are examples:
using System;
public class Exercise
{
static void Main(string[] args)
{
string firstName;
dynamic lastName;
}
}
You can also use the var keyword to declare a string variable. In this case, you must initialize the variable.
An Empty String
A string is referred to as empty if it contains no characters at all. To create such a string, you can declare a string or String variable and initialize it with empty double-quotes. Here is an example:
string empty = "";
To support the ability to create an empty string, the String class is equipped with a static field named Empty:
public static readonly string Empty
The String.Empty field allows you to initialize a string variable with empty space or to reset a string to an empty value. Here are examples:
using System;
public class Exercise
{
static void Main(string[] args)
{
string firstName = string.Empty;
var middleName = string.Empty;
dynamic lastName = string.Empty;
}
}
Converting a Value or an Object to a String
To allow you to convert any value or object to a string, the object data type (that is, its equivalent Object class) is equipped with a method named ToString Most classes override this method. If you want a particular implementation of this method for your class, you must override it.
The Length of a String
The length of a string, also referred to as its size, is the number of symbols or charaters it contains. To let you get this information, The String class is equipped with a property named Length. Here is an example of using it:
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
string gender = "Female";
WriteLine("{0} contains {1} characters", gender, gender.Length);
WriteLine("===============================");
return 22_813_729;
}
}
This would produce:
Female contains 6 characters =============================== Press any key to continue . . .
Practical Learning: Introducing the Number of Characters
using System;
using System.Windows.Forms;
namespace AccountValidation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtNewPassword_Leave(object sender, EventArgs e)
{
string strNewPassword = txtNewPassword.Text;
int length = strNewPassword.Length;
txtCharacters.Text = length.ToString();
}
}
}
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:
using System;
public class Exercise
{
static void Main(string[] args)
{
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:
using System;
public class Exercise
{
static void Main(string[] args)
{
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; public class Exercise { public static int Main(string[] args) { string gender = "Female"; WriteLine("Gender: {0}", gender); WriteLine("-------------------------------"); WriteLine("Individual Characters"); foreach(char c in gender) WriteLine("Character: {0}", c); WriteLine("==============================="); return 22_813_729; } }
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 System; using static System.Console; public class Exercise { public static int Main(string[] args) { 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("==============================="); return 22_813_729; } }
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.
Practical Learning: Checking the Types of Characters
using System;
using System.Windows.Forms;
namespace AccountValidation1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtNewPassword_Leave(object sender, EventArgs e)
{
int digits = 0, symbols = 0, lowercase = 0, uppercase = 0;
string strNewPassword = txtNewPassword.Text;
int length = strNewPassword.Length;
for (int i = 0; i < length; i++)
{
if (Char.IsDigit(strNewPassword[i]))
digits++;
if (Char.IsSymbol(strNewPassword[i]) || Char.IsPunctuation(strNewPassword[i]))
symbols++;
if (Char.IsLower(strNewPassword[i]))
lowercase++;
if (Char.IsUpper(strNewPassword[i]))
uppercase++;
}
txtDigits.Text = digits.ToString();
txtSymbols.Text = symbols.ToString();
txtCharacters.Text = length.ToString();
txtLowercaseLetters.Text = lowercase.ToString();
txtUppercaseLetters.Text = uppercase.ToString();
}
}
}
|
||
Previous | Copyright © 2001-2021, FunctionX | Next |
|