Introduction to Characters
Introduction to Characters
Fundamentals of Characters
Introduction
A character is a recognizable symbol. It can be:
Practical Learning: Introducing Characters
A Character Value
To represent a character, include it between two single-quotes. Examples are 'm', '$', ' ', '*', and '1'
A Type of Character
Introduction
To support characters; the C# language provides a data type named char. The char data type is identified in the .NET Framework by a structure named Char. In fact, the char data type gets all of its characteristics and functionalities from the Char structure.
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 int Main()
{
char gender = 'm';
char moneySymbol = '$';
Char multiplication = '*';
Char numberOne = '1';
return 0;
}
}
You can also use the var or the dynamic keyword if you are initializing the variable.
A Constant Character
To create a constant character, precede the data type with the const keyword. Here are two examples:
using System;
public class Exercise
{
static int Main()
{
const char currency = '$';
const char emailSymbol = '@';
return 0;
}
}
Presenting a Character
To display a character to the computer screen, you can pass its value or variable to the Console.Write() or the Console.WriteLine() methods. Here are examples:
using static System.Console; public class Exercise { static int Main() { const char empty = ' '; const char equals = '='; const char currency = '$'; const char emailSymbol = '@'; string username = "rcarryon"; string fName = "Raymond"; string lName = "Carryon"; const string domain = "race-to-the-bottom.com"; double hourlySalary = 19.75; Write("Employee: " + fName); Write(empty); WriteLine(lName); Write("Contact:"); Write(' '); Write(username); Write(emailSymbol); WriteLine(domain); Write("Weekly Salary: "); Write(currency); Write(hourlySalary); Write(empty); Write('*'); Write(empty); Write(40); Write(empty); Write(equals); Write(empty); Write(currency); WriteLine(hourlySalary * 40); WriteLine("=========================================="); return 0; } }
This would produce:
Employee: Raymond Carryon Contact: rcarryon@race-to-the-bottom.com Weekly Salary: $19.75 * 40 = $790 ========================================== Press any key to continue . . .
Requesting a Character
As mentioned in previously lessons, the Console.ReadLine() method returns a string that a user types. To let you convert the value to a character, the char data type (actually the Char structure) is equipped with a method named Parse. You can pass a Console.ReadLine() call to this method.
Primary Operations on Characters
An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line. An escape sequence is represented by a backslash character, \, followed by another character or symbol. For example, the escape sequence that moves to the next line is \n. An escape can be included in single-quotes as in '\n'. It can also be provided in double-quotes as "\n". |
Note: All C-based languages support these escape sequencces |
The C# language recognizes other escape sequences:
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 include it in a string, you can pass it in a single or double-quoted string of Console.Write() or Console.WriteLine(), or you can pass it by itself in a single or double-quoted string of Console.Write() or Console.WriteLine(). Here are examples:
using static System.Console; public class Exercise { static int Main() { const char empty = ' '; const char equals = '='; const char currency = '$'; const char emailSymbol = '@'; string username = "rcarryon"; string fName = "Raymond"; string lName = "Carryon"; const string domain = "race-to-the-bottom.com"; double hourlySalary = 19.75; string ws = "Weekly Salary:\t"; Write("Employee:"); Write('\t'); Write(fName); Write(empty); Write(lName); Write('\n'); Write("Contact:\t"); Write(username); Write(emailSymbol); Write(domain); Write('\n'); Write(ws); Write(currency); Write(hourlySalary); Write(empty); Write('*'); Write(empty); Write(40); Write(empty); Write(equals); Write(empty); Write(currency); Write(hourlySalary * 40); Write("\n"); WriteLine("=================================================="); return 0; } }
To use an escape sequence, you can also first declare a char variable and initialize it with the desired escape sequence in single-quotes.
Reading a Character
As you may know already, each letter of the alphabet is represented on the keyboard by a key. Other symbols, readable (such as #, @, or $) or not (such as Shift, Ctrl, or Enter) are also represented. To get the letter or the action that those keys represent, the Console class is equipped with a method named ReadKey that is overloaded with two versions. One of the versions uses the following syntax:
public static ConsoleKeyInfo ReadKey();
This method takes no argument and produces a value of type ConsoleKeyInfo. To get the value returned by this method, you can declare a ConsoleKeyInfo variable and assign it to the calling of this method.
If the user presses a key for a letter or a readable symbol (such as #, !, /, or %), to recognize the key that was pressed, the ConsoleKeyInfo class is equipped with a member named KeyChar. Here is an example of getting the letter:
using System; public class Exercise { static int Main() { ConsoleKeyInfo cki = new ConsoleKeyInfo(); Console.Write("Press a key: "); cki = System.Console.ReadKey(); Console.WriteLine(); Console.Write("You pressed: "); Console.WriteLine(cki.KeyChar); return 0; } }
If the key that the user pressed is not a readable symbol such as the Space Bar, a Ctrl key, or Enter, to recognize it, the ConsoleKeyInfo class is equipped with a member named Key. Here is an example of using it:
using System;
public class Exercise
{
static int Main()
{
ConsoleKeyInfo cki = new ConsoleKeyInfo();
Console.Write("Press a key: ");
cki = System.Console.ReadKey();
Console.WriteLine();
Console.Write("You pressed: ");
Console.WriteLine(cki.Key);
return 0;
}
}
Character Addition
The char data type (actually the Char structure) supports the addition operation. You can add character values as in 'i' + 'e', which would produce ie. You can add two variables that hold character values. You can add a string to a character and vice-versa.
Characters and Conditional Statements
A character can be used in any of the conditional statements applied to numbers.
Practical Learning: Introducing Character Variables
using static System.Console; namespace VaccinationCampaign1 { public class VaccinationCampaign { public static int Main() { char pregnancy = ' '; string patientGender = ""; string patientLastName = ""; string patientFirstName = ""; string patientMiddleName = ""; string patientAgeRange = "Unknown", vaccinations = "None"; WriteLine("Department of Health"); WriteLine("-------------------------------------------------------"); WriteLine("Patient's Diagnosis"); Write("Patient's First Name: "); patientFirstName = ReadLine(); Write("Patient's Last Name: "); patientLastName = ReadLine(); Write("Patient's Middle Name (if none, type N/A): "); patientMiddleName = ReadLine(); Write("Patient's Gender (M - Male, F - Female): "); char gender = char.Parse(ReadLine()); WriteLine("Patients Age Ranges"); WriteLine(" B - Baby/Toddler"); WriteLine(" K - Kid"); WriteLine(" T - Teen/Young Adult"); WriteLine(" A - Adult"); Write("Type the patient's age range: "); char ageRange = char.Parse(ReadLine()); switch (gender) { case 'f': case 'F': patientGender = "Female"; break; case 'M': case 'm': patientGender = "Male"; break; default: patientGender = "Unknown"; break; } switch (ageRange) { case 'b': case 'B': patientAgeRange = "Baby/Toddler/Newborn"; vaccinations = "The following vaccinations are recommended for toodlers (whether newborn or babies):\n" + " 1. HepB: 1 month to 2 months and 6 to 19 months.\n" + " 2. RV: 2, 4, and 6 months.\n" + " 3. DTaP: 2, 4, 6, and 15 months, and 4-6 years.\n" + " 4. Hib and PCV13: 2, 4, 6, and 12 months.\n" + " 5. IPV: 2, 4, and 6 months, then 4-6 months.\n" + " 6. Hepatitis A: 18 to 23 months.\n" + " All vaccinations must be subject to a physician's recommendations and monitoring.\n" + " For more informaiton, refer to https://www.cdc.gov/vaccines/schedules/easy-to-read/child-easyread.html"; break; case 'K': case 'k': patientAgeRange = "Kid/Child"; vaccinations = "The following vaccinations are recommendeded for children:\n" + " 1. Hepatitis B: 18 months.\n" + " 2. Diphtheria, tetanus, & acellular pertussis: 18 months, then 4-6 years.\n" + " 3. Inactivated poliovirus: 18 months, then 4-6 years.\n" + " 4. Influenza: Annual Vaccination.\n" + " 4. Measles, mumps, rubella and Varicella: 4-6 years.\n" + " 5. Rotavirus, Haemophilus influenzae type b, Pneumococcal conjugate: Consult a physician.\n" + " All vaccinations must be subject to a schedule created or approved by a physician.\n" + " For more informaiton, refer to https://www.cdc.gov/vaccines/schedules/easy-to-read/child-easyread.html"; break; case 't': case 'T': patientAgeRange = "Teenager/Young Adult"; if( (gender == 'f') || (gender == 'F') ) { Write("Is the patient pregnant (Y/N)? "); pregnancy = char.Parse(ReadLine()); if( (pregnancy == 'y') || (pregnancy == 'Y') ) { vaccinations = "The following vaccinations are recommended for pregnant girls:\n" + " 1. Influenza (Inactivated)\n" + " 2. Tdap\n" + " 3. Hepatitis B: The patient should consult her physician\n" + " Other vaccinations should be scheduled and followed by a physician."; } else { vaccinations = "The following vaccinations are recommended for young adults:\n" + " 1. Diphtheria, tetanus, & acellular pertussis: 18 months, then 4-6 months.\n" + " 2. Inactivated poliovirus: 18 months, then 4-6 years.\n" + " 3. Influenza: Annual Vaccination.\n" + " 4. Meningococcal: 11-12 years and 16 years.\n" + " 5. Tetanus, diphtheria, & acellular pertussis, and Human papillomavirus: 11-12 months.\n" + " 6. Meningococcal B: 11 to 18 years.\n" + " 7. Pneumococcal polysaccharide: 2-3 years to 17-19.\n" + " For more information, refer to https://www.cdc.gov/vaccines/schedules/hcp/imz/child-adolescent.html"; } } else // if( gender == 'M') { vaccinations = "The following vaccinations are recommended for young adults:\n" + " 1. Diphtheria, tetanus, & acellular pertussis: 18 months, then 4-6 months.\n" + " 2. Inactivated poliovirus: 18 months, then 4-6 years.\n" + " 3. Influenza: Annual Vaccination.\n" + " 4. Meningococcal: 11-12 years and 16 years.\n" + " 5. Tetanus, diphtheria, & acellular pertussis, and Human papillomavirus: 11-12 months.\n" + " 6. Meningococcal B: 11 to 18 years.\n" + " 7. Pneumococcal polysaccharide: 2-3 years to 17-19.\n" + " For more information, refer to https://www.cdc.gov/vaccines/schedules/hcp/imz/child-adolescent.html"; } break; case 'a': case 'A': patientAgeRange = "Adult"; if( (gender == 'F') || (gender == 'f') ) { Write("Is the patient pregnant (Y/N)? "); pregnancy = char.Parse(ReadLine()); if (pregnancy == 'Y') { vaccinations = "The following vaccinations are recommended for pregnant women:\n" + " 1. Influenza (Inactivated)\n" + " 2. Tdap\n" + " 3. Hepatitis B: The patient should consult her physician\n" + " Other vaccinations should be scheduled and followed by a physician."; } else // if (pregnancy == 'N') { vaccinations = "The following vaccinations are recommended for adult females: Flu, Tdap or Td (Tetanus, diphtheria, pertussis),\n" + " Shingles (Zoster), Pneumococcal, Meningococcal, MMR (Measles, mumps, rubella),\n" + " HPV (Human papillomavirus), Chickenpox (Varicella), Hepatitis A, Hepatitis B,\n" + " Hib (Haemophilus, influenzae.\n" + " For more information, refer to https://www.cdc.gov/vaccines/schedules/downloads/adult/adult-schedule-easy-read.pdf"; } } else // if( gender == 'M') { vaccinations = "The following vccinations are recommended for adult males: Flu, Tdap or Td (Tetanus, diphtheria, pertussis),\n" + " Meningococcal, MMR (Measles, mumps, rubella),\n" + " HPV (Human papillomavirus), Hib (Haemophilus, influenzae.\n" + " For more information, refer to https://www.cdc.gov/vaccines/schedules/downloads/adult/adult-schedule-easy-read.pdf"; } break; default: break; } Clear(); WriteLine("Department of Health"); WriteLine("-------------------------------------------------------------------"); WriteLine("Patient's Diagnosis"); Write("Patient Name: " + patientFirstName); if (patientMiddleName != "N/A") Write(" " + patientMiddleName); WriteLine(" " + patientLastName); WriteLine("Gender: " + patientGender); WriteLine("Age Range: " + patientAgeRange); WriteLine("-------------------------------------------------------------------"); WriteLine(vaccinations); WriteLine("================================================================="); return 0; } } }
Department of Health ------------------------------------------------------- Patient's Diagnosis Patient's First Name:
Department of Health ------------------------------------------------------- Patient's Diagnosis Patient's First Name: James Patient's Last Name: Dayne Patient's Middle Name (if none, type N/A): Joseph Patient's Gender (M - Male, F - Female): M Patients Age Ranges B - Baby/Toddler K - Kid T - Teen/Young Adult A - Adult Type the patient's age range: A
Department of Health ------------------------------------------------------------------- Patient's Diagnosis Patient Name: James Joseph Dayne Gender: Male Age Range: Adult ------------------------------------------------------------------- The following vccinations are recommended for adult males: Flu, Tdap or Td (Teta nus, diphtheria, pertussis), Meningococcal, MMR (Measles, mumps, rubella), HPV (Human papillomavirus), Hib (Haemophilus, influenzae. For more information, refer to https://www.cdc.gov/vaccines/schedules/downloads /adult/adult-schedule-easy-read.pdf ================================================================= Press any key to continue . . .
Characters and Classes
A Character-Based Field
In a class, you can create a filed that uses the char data type or the Char structure as its type. Here is an example:
public class Employee
{
private char mi;
}
In the same way, in the body of a class, you can declare a variable of type char or Char.
A Character-Based Property
A property can be create as a character or Char type. Proceed as we have done in previous lessons. Here are examples:
public class Employee { // Private field private char mi; // A completely defined property public char MiddleInitial { get { return mi; } set { mi = value; } } // An automatically defined property public char Gender { get; set; } }
If you want to initialize an automatic property when creating it, assign a single-quoted value to it. .
Passing a Character to a Method
Like a normal value, a character can be passed to a method as argument. 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 Patient { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string AgeRange(char sex) { if ((sex == 'm') || (sex == 'M')) return "Male"; else if ((sex == 'f') || (sex == 'F')) return "Female"; return "Unknown"; } //public char Gender { get; set; } } public class Exercise { private static void Main() { Patient person = new Patient(); person.FirstName = "Joshua"; person.MiddleName = "Litterans"; person.LastName = "Romano"; WriteLine("Patient Name: " + person.FirstName + " " + person.MiddleName + " " + person.LastName); WriteLine("Age Rage: " + person.AgeRange('m')); WriteLine("======================================"); return; } }
This would produce:
Patient Name: Joshua Litterans Romano Age Rage: Male ====================================== 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".
Practical Learning: Converting Characters
using static System.Console; namespace VaccinationCampaign1 { public class VaccinationCampaign { public static int Main() { char pregnancy = ' '; string patientGender = ""; string patientLastName = ""; string patientFirstName = ""; string patientMiddleName = ""; string patientAgeRange = "Unknown", vaccinations = "None"; WriteLine("Department of Health"); WriteLine("-------------------------------------------------------"); WriteLine("Patient's Diagnosis"); Write("Patient's First Name: "); patientFirstName = ReadLine(); Write("Patient's Last Name: "); patientLastName = ReadLine(); Write("Patient's Middle Name (if none, type N/A): "); patientMiddleName = ReadLine(); Write("Patient's Gender (M - Male, F - Female): "); char gender = char.Parse(ReadLine()); WriteLine("Patients Age Ranges"); WriteLine(" B - Baby/Toddler"); WriteLine(" K - Kid"); WriteLine(" T - Teen/Young Adult"); WriteLine(" A - Adult"); Write("Type the patient's age range: "); char ageRange = char.Parse(ReadLine()); switch(char.ToLower(gender)) { case 'f': patientGender = "Female"; break; case 'm': patientGender = "Male"; break; default: patientGender = "Unknown"; break; } switch(char.ToUpper(ageRange)) { case 'B': patientAgeRange = "Baby/Toddler/Newborn"; vaccinations = "The following vaccinations are recommended for toodlers (whether newborn or babies):\n" + " 1. HepB: 1 month to 2 months and 6 to 19 months.\n" + " 2. RV: 2, 4, and 6 months.\n" + " 3. DTaP: 2, 4, 6, and 15 months, and 4-6 years.\n" + " 4. Hib and PCV13: 2, 4, 6, and 12 months.\n" + " 5. IPV: 2, 4, and 6 months, then 4-6 months.\n" + " 6. Hepatitis A: 18 to 23 months.\n" + " All vaccinations must be subject to a physician's recommendations and monitoring.\n" + " For more informaiton, refer to https://www.cdc.gov/vaccines/schedules/easy-to-read/child-easyread.html"; break; case 'K': patientAgeRange = "Kid/Child"; vaccinations = "The following vaccinations are recommendeded for children:\n" + " 1. Hepatitis B: 18 months.\n" + " 2. Diphtheria, tetanus, & acellular pertussis: 18 months, then 4-6 years.\n" + " 3. Inactivated poliovirus: 18 months, then 4-6 years.\n" + " 4. Influenza: Annual Vaccination.\n" + " 4. Measles, mumps, rubella and Varicella: 4-6 years.\n" + " 5. Rotavirus, Haemophilus influenzae type b, Pneumococcal conjugate: Consult a physician.\n" + " All vaccinations must be subject to a schedule created or approved by a physician.\n" + " For more informaiton, refer to https://www.cdc.gov/vaccines/schedules/easy-to-read/child-easyread.html"; break; case 'T': patientAgeRange = "Teenager/Young Adult"; if(char.ToLower(gender) == 'f') { Write("Is the patient pregnant (Y/N)? "); pregnancy = char.Parse(ReadLine()); if ((pregnancy == 'y') || (pregnancy == 'Y')) { vaccinations = "The following vaccinations are recommended for pregnant girls:\n" + " 1. Influenza (Inactivated)\n" + " 2. Tdap\n" + " 3. Hepatitis B: The patient should consult her physician\n" + " Other vaccinations should be scheduled and followed by a physician."; } else { vaccinations = "The following vaccinations are recommended for young adults:\n" + " 1. Diphtheria, tetanus, & acellular pertussis: 18 months, then 4-6 months.\n" + " 2. Inactivated poliovirus: 18 months, then 4-6 years.\n" + " 3. Influenza: Annual Vaccination.\n" + " 4. Meningococcal: 11-12 years and 16 years.\n" + " 5. Tetanus, diphtheria, & acellular pertussis, and Human papillomavirus: 11-12 months.\n" + " 6. Meningococcal B: 11 to 18 years.\n" + " 7. Pneumococcal polysaccharide: 2-3 years to 17-19.\n" + " For more information, refer to https://www.cdc.gov/vaccines/schedules/hcp/imz/child-adolescent.html"; } } else // if(char.ToLower(gender) == 'm') { vaccinations = "The following vaccinations are recommended for young adults:\n" + " 1. Diphtheria, tetanus, & acellular pertussis: 18 months, then 4-6 months.\n" + " 2. Inactivated poliovirus: 18 months, then 4-6 years.\n" + " 3. Influenza: Annual Vaccination.\n" + " 4. Meningococcal: 11-12 years and 16 years.\n" + " 5. Tetanus, diphtheria, & acellular pertussis, and Human papillomavirus: 11-12 months.\n" + " 6. Meningococcal B: 11 to 18 years.\n" + " 7. Pneumococcal polysaccharide: 2-3 years to 17-19.\n" + " For more information, refer to https://www.cdc.gov/vaccines/schedules/hcp/imz/child-adolescent.html"; } break; case 'A': patientAgeRange = "Adult"; if(char.ToLower(gender) == 'F') { Write("Is the patient pregnant (Y/N)? "); pregnancy = char.Parse(ReadLine()); if(char.ToUpper(pregnancy) == 'Y') { vaccinations = "The following vaccinations are recommended for pregnant women:\n" + " 1. Influenza (Inactivated)\n" + " 2. Tdap\n" + " 3. Hepatitis B: The patient should consult her physician\n" + " Other vaccinations should be scheduled and followed by a physician."; } else // if(char.ToUpper(pregnancy) == 'N') { vaccinations = "The following vaccinations are recommended for adult females: Flu, Tdap or Td (Tetanus, diphtheria, pertussis),\n" + " Shingles (Zoster), Pneumococcal, Meningococcal, MMR (Measles, mumps, rubella),\n" + " HPV (Human papillomavirus), Chickenpox (Varicella), Hepatitis A, Hepatitis B,\n" + " Hib (Haemophilus, influenzae.\n" + " For more information, refer to https://www.cdc.gov/vaccines/schedules/downloads/adult/adult-schedule-easy-read.pdf"; } } else // if(char.ToUpper(gender) == 'M') { vaccinations = "The following vccinations are recommended for adult males: Flu, Tdap or Td (Tetanus, diphtheria, pertussis),\n" + " Meningococcal, MMR (Measles, mumps, rubella),\n" + " HPV (Human papillomavirus), Hib (Haemophilus, influenzae.\n" + " For more information, refer to https://www.cdc.gov/vaccines/schedules/downloads/adult/adult-schedule-easy-read.pdf"; } break; default: break; } Clear(); WriteLine("Department of Health"); WriteLine("-------------------------------------------------------------------"); WriteLine("Patient's Diagnosis"); Write("Patient Name: " + patientFirstName); if (patientMiddleName != "N/A") Write(" " + patientMiddleName); WriteLine(" " + patientLastName); WriteLine("Gender: " + patientGender); WriteLine("Age Range: " + patientAgeRange); WriteLine("-------------------------------------------------------------------"); WriteLine(vaccinations); WriteLine("================================================================="); return 0; } } }
Department of Health ------------------------------------------------------- Patient's Diagnosis Patient's First Name:
Department of Health ------------------------------------------------------- Patient's Diagnosis Patient's First Name: Hermine Patient's Last Name: Ake Patient's Middle Name (if none, type N/A): N/A Patient's Gender (M - Male, F - Female): f Patients Age Ranges B - Baby/Toddler K - Kid T - Teen/Young Adult A - Adult Type the patient's age range: B
Department of Health ------------------------------------------------------------------- Patient's Diagnosis Patient Name: Hermine Ake Gender: Female Age Range: Baby/Toddler/Newborn ------------------------------------------------------------------- The following vaccinations are recommended for toodlers (whether newborn or babi es): 1. HepB: 1 month to 2 months and 6 to 19 months. 2. RV: 2, 4, and 6 months. 3. DTaP: 2, 4, 6, and 15 months, and 4-6 years. 4. Hib and PCV13: 2, 4, 6, and 12 months. 5. IPV: 2, 4, and 6 months, then 4-6 months. 6. Hepatitis A: 18 to 23 months. All vaccinations must be subject to a physician's recommendations and monitorin g. For more informaiton, refer to https://www.cdc.gov/vaccines/schedules/easy-to-r ead/child-easyread.html ================================================================= Press any key to continue . . .
The Characters of a String
A String as an Array of Characters
A string is a group, or an array, of characters. After declaring and initializing a string, it is considered an array of symbols 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 type uses 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];
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 { private static void Main() { string country = "Angola"; WriteLine("Country: " + country); WriteLine("---------------------"); WriteLine("Individual Characters"); foreach(char letter in country) WriteLine("Character: " + letter); WriteLine("============================================"); return; } }
This would produce:
Country: Angola --------------------- Individual Characters Character: A Character: n Character: g Character: o Character: l Character: a ============================================ Press any key to continue . . .
Practical Learning: Using the Characters of a String
using static System.Console;
namespace VaccinationCampaign1
{
public class VaccinationCampaign
{
public static int Main()
{
. . .
Clear();
WriteLine("Department of Health");
WriteLine("-------------------------------------------------------------------");
WriteLine("Patient's Diagnosis");
Write("Patient Name: " + patientFirstName);
if (patientMiddleName != "N/A")
Write(" " + patientMiddleName[0] + ".");
WriteLine(" " + patientLastName);
WriteLine("Gender: " + patientGender);
WriteLine("Age Range: " + patientAgeRange);
WriteLine("-------------------------------------------------------------------");
WriteLine(vaccinations);
WriteLine("=================================================================");
return 0;
}
}
}
Department of Health ------------------------------------------------------- Patient's Diagnosis Patient's First Name:
Department of Health ------------------------------------------------------- Patient's Diagnosis Patient's First Name: Marie-Jeanne Patient's Last Name: Collins Patient's Middle Name (if none, type N/A): Andrea Patient's Gender (M - Male, F - Female): f Patients Age Ranges B - Baby/Toddler K - Kid T - Teen/Young Adult A - Adult Type the patient's age range: t Is the patient pregnant (Y/N)? y
Department of Health ------------------------------------------------------------------- Patient's Diagnosis Patient Name: Marie-Jeanne Andrea Collins Gender: Female Age Range: Teenager/Young Adult ------------------------------------------------------------------- The following vaccinations are recommended for pregnant girls: 1. Influenza (Inactivated) 2. Tdap 3. Hepatitis B: The patient should consult her physician Other vaccinations should be scheduled and followed by a physician. ================================================================= Press any key to continue . . .
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 get this information, apply the Length property to either a constant string or a String variable. Here is an example of using it:
using static System.Console; public class Exercise { private static void Main() { string country = "Madagascar"; string city = "Antananarivo"; int len = "Antananarivo".Length; WriteLine("Country: {0} (contains {1} characters).", country, country.Length); WriteLine("Capital: " + city); WriteLine("Antananarivo contains " + len + " characters"); WriteLine("============================================"); return; } }
This would produce:
Country: Madagascar (contains 10 characters). Capital: Antananarivo Antananarivo contains 12 characters ============================================ Press any key to continue . . .
Converting a Character to a String
To let you convert a character to a string, the char type has an overriden version of the Object.ToString() method. You can call this method on a char-based variable. Here is an example:
using static System.Console; public class Exercise { private static void Main() { string firstName = "Jenny"; char mi = 'M'; string lastName = "Goodwin"; WriteLine("Full Name: {0} {1} {2}", firstName, mi.ToString(), lastName); return; } }
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; public class Exercise { private static void Main() { WriteLine(" Proposition Conclusion"); WriteLine("------------------------------------"); WriteLine(" q is a Letter {0}", char.IsLetter('q')); WriteLine(" a is a lowercase letter {0}", char.IsLower('a')); WriteLine(" W is an uppercase letter {0}", char.IsUpper('W')); BackgroundColor = System.ConsoleColor.Blue; ForegroundColor = System.ConsoleColor.Cyan; WriteLine(" 1 is a lowercase letter {0}", char.IsLower('1')); ResetColor(); WriteLine(" 1 is a digit {0}", char.IsDigit('1')); WriteLine(" w is a letter or a digit {0}", char.IsLetterOrDigit('w')); WriteLine(" 3 is a letter or a digit {0}", char.IsLetterOrDigit('3')); BackgroundColor = System.ConsoleColor.Blue; ForegroundColor = System.ConsoleColor.Cyan; WriteLine(" # is a letter or a digit {0}", char.IsLetterOrDigit('#')); ResetColor(); WriteLine(" 0 is a number {0}", char.IsNumber('0')); WriteLine(" _ is a punctuation mark {0}", char.IsPunctuation('_')); BackgroundColor = System.ConsoleColor.Blue; ForegroundColor = System.ConsoleColor.Cyan; WriteLine(" # is a lowercase letter {0}", char.IsLower('#')); ResetColor(); WriteLine(" # is a punctuation mark {0}", char.IsPunctuation('#')); WriteLine(" \\ is a punctuation mark {0}", char.IsPunctuation('\\')); WriteLine(" is a white space {0}", char.IsWhiteSpace(' ')); WriteLine(" is a separator {0}", char.IsSeparator(' ')); WriteLine(" + is a symbol {0}", char.IsSymbol('+')); WriteLine("======================================"); return; } }
This would produce:
You can apply a conditional statement to a method to find out what character is at a certain position.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|