Fundamentals of Strings

Introduction

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 C# language provides a data type named string. To support strings, the .NET Framework provides a class named String. The C# string data type is an adaptation of the .NET Framework's String class. This means that the string data type gets all of its characteristics and functionalities from the String class.

To declare a string variable, use the string data type or the dynamic keyword. Alternatively, you can use the String type, in which case you should include the System namespace before declare the variable (using System;. If you can initialize the variable when declaring it, you can use the var keyword as type. Here are examples:

public class Exercise
{
    static void Main()
    {
        string firstName;
        dynamic lastName;
    }
}

You can also use the var keyword to declare a string variable. In this case, you must initialize the variable.

Practical LearningPractical Learning: Introducing Strings

  1. Start Microsoft Visual Studio
  2. On the main menu, click Project -> New -> Project...
  3. In the middle frame, make sure Empty Project (.NET Framework).
    Change the name to PayrollPreparation2
  4. Press Enter
  5. To create a new class, on the main menu, click Project -> Add Class...
  6. Type PayrollPreparation as the name of the class
  7. Click Add
  8. Change the document as follows:
    using static System.Console;
    
    namespace PayrollPreparation2
    {
        public class PayrollPreparation
        {
            public static void Main()
            {
                WriteLine("Account Creation");
                WriteLine("---------------------------------");
                WriteLine("Provide the following information");
                Write("First Name:       ");
                string strFirstName = ReadLine();
                Write("Middle Name:      ");
                string strMiddleName = ReadLine();
                Write("Last Name:        ");
                string strLastName = ReadLine();
                WriteLine("---------------------------------");
                Write("Password:         ");
                string strNewPassword = ReadLine();
                Write("Confirm Password: ");
                string strConfirmPassword = ReadLine();
                
                Clear();
    
                WriteLine("Account Summary");
                WriteLine("------------------------------");
                WriteLine("First Name:  " + strFirstName);
                WriteLine("Middle Name: " + strMiddleName);
                WriteLine("Last Name:   " + strLastName);
    
                WriteLine("Password:    " + strNewPassword);
                WriteLine("==============================");
    
                return;
            }
        }
    }
  9. To execute, on the main menu, click Debug -> Start Without Debugging:
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:
  10. Type some values as follows:
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:       Roberto
    Middle Name:      Carlos
    Last Name:        Solorio
    --------------------------------
    Password:         $Outh0D@kota!9
    Confirm Password: SouthDakota
  11. Press Enter:
    Account Summary
    ------------------------------
    First Name:  Roberto
    Middle Name: Carlos
    Last Name:   Solorio
    Password:    $Outh0D@kota!9
    ==============================
    Press any key to continue . . .
  12. Press Enter to close the window and return to your programming environment

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:

public class Exercise
{
    private static void Main()
    {
        string firstName = string.Empty;
        var middleName = string.Empty;
        dynamic lastName = string.Empty;

        return;
    }
}

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. Therefore, to convert a number or Boolean value to string, you can call this method on it.

Practical LearningPractical Learning: Converting an Object to a String

The Characters of a String

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.

Practical LearningPractical Learning: Introducing the Number of Characters

  1. Change the code as follows:
    using static System.Console;
    
    namespace PayrollPreparation2
    {
        public class PayrollPreparation
        {
            public static void Main()
            {
                string strUsername = string.Empty;
    
                WriteLine("Account Creation");
                WriteLine("---------------------------------");
                WriteLine("Provide the following information");
                Write("First Name:       ");
                string strFirstName = ReadLine();
                Write("Middle Name:      ");
                string strMiddleName = ReadLine();
                Write("Last Name:        ");
                string strLastName = ReadLine();
                WriteLine("---------------------------------");
                Write("Password:         ");
                string strNewPassword = ReadLine();
                Write("Confirm Password: ");
                string strConfirmPassword = ReadLine();
    
                int length = strNewPassword.Length;
    
                Clear();
    
                WriteLine("Account Summary");
                WriteLine("----------------------------");
                WriteLine("First Name:      " + strFirstName);
                WriteLine("Middle Name:     " + strMiddleName);
                WriteLine("Last Name:       " + strLastName);
                WriteLine("-------------------------------------------");
                WriteLine("Password:        " + strNewPassword);
                WriteLine("Password Length: {0} symbol(s)/character(s)", length.ToString());
                WriteLine("===========================================");
    
                return;
            }
        }
    }
  2. To execute the project, on the main menu, click Debug -`Start Without Debugging:
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:
  3. Type some values as follows (when prompted for the middle name, you will simply press Enter):
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:       Andrew
    Middle Name:      Daniel
    Last Name:        Grossman
    ---------------------------------
    Password:         Password1
    Confirm Password: OnePassword
  4. Press Enter:
    Account Summary
    ----------------------------
    First Name:      Andrew
    Middle Name:     Daniel
    Last Name:       Grossman
    -------------------------------------------
    Password:        Password1
    Password Length: 9 symbol(s)/character(s)
    ===========================================
    Press any key to continue . . .
  5. Press Enter to close the window and return to your programming environment

Categories of Characters

To let identify a symbol used in a string, the char data type from the Char structure is equipped with static methods for each category of character. Each method takes two arguments and returns a Boolean value. The first argument is the string to be considered. The second argument is the position where the character is. The method examines the character or symbol at that position. If the character you are looking is found at that position, the method returns true. The syntaxes of the methods are:

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

Practical LearningPractical Learning: Idenfying a Character

  1. Change the document as follows:
    using static System.Console;
    
    namespace PayrollPreparation2
    {
        public class PayrollPreparation
        {
            public static void Main()
            {
                int digits = 0;
                int symbols = 0;
                int letters = 0;
                int numbers = 0;
                int lowercase = 0;
                int uppercase = 0;
                int separators = 0;
                int whiteSpaces = 0;
                int punctuations = 0;
                int letterOrDigits = 0;
    
                WriteLine("Account Creation");
                WriteLine("---------------------------------");
                WriteLine("Provide the following information");
                Write("First Name:       ");
                string strFirstName = ReadLine();
                Write("Middle Name:      ");
                string strMiddleName = ReadLine();
                Write("Last Name:        ");
                string strLastName = ReadLine();
                WriteLine("---------------------------------");
                Write("Password:         ");
                string strNewPassword = ReadLine();
                Write("Confirm Password: ");
                string strConfirmPassword = ReadLine();
    
                int length = strNewPassword.Length;
    
                for (int i = 0; i < strNewPassword.Length - 1; i++)
                {
                    if (char.IsWhiteSpace(strNewPassword, i))
                        whiteSpaces++;
                    if (char.IsLetter(strNewPassword, i))
                        letters++;
                    if (char.IsDigit(strNewPassword, i))
                        digits++;
                    if (char.IsLetterOrDigit(strNewPassword, i))
                        letterOrDigits++;
                    if (char.IsNumber(strNewPassword, i))
                        numbers++;
                    if (char.IsPunctuation(strNewPassword, i))
                        punctuations++;
                    if (char.IsSeparator(strNewPassword, i))
                        separators++;
                    if (char.IsSymbol(strNewPassword, i))
                        symbols++;
                    if (char.IsLower(strNewPassword, i))
                        lowercase++;
                    if (char.IsUpper(strNewPassword, i))
                        uppercase++;
                }
    
                Clear();
    
                WriteLine("Account Summary");
                WriteLine("----------------------------");
                WriteLine("First Name:      " + strFirstName);
                WriteLine("Middle Name:     " + strMiddleName);
                WriteLine("Last Name:       " + strLastName);
                WriteLine("-------------------------------------------");
                WriteLine("Password:        " + strNewPassword);
                WriteLine("Password Length: {0} symbol(s)/character(s)", length.ToString());
                WriteLine("-------------------------------------------");
                WriteLine("The password contains:");
                WriteLine(" " + whiteSpaces + " white space(s)");
                WriteLine(" " + symbols + " symbol(s)");
                WriteLine(" " + digits + " digit(s)");
                WriteLine(" " + letters   + " letter(s)");
                WriteLine(" " + letterOrDigits + " letter(s) or digit(s)");
                WriteLine(" " + numbers + " number(s)");
                WriteLine(" " + punctuations + " punctuation mark(s)");
                WriteLine(" " + separators + " separator character(s)");
                WriteLine(" " + lowercase + " lowercase letter(s)");
                WriteLine(" " + uppercase + " uppercase letter(s)");
                WriteLine("===========================================");
    
                return;
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:
  3. Type some values as follows:
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:       Roberto
    Middle Name:      Anthony
    Last Name:        Solorio
    ---------------------------------
    Password:         =88 $Outh D@kota #40
    Confirm Password: =88 $Outh D@kota #40
  4. Press Enter:
    Account Summary
    ----------------------------
    First Name:      Roberto
    Middle Name:     Anthony
    Last Name:       Solorio
    -------------------------------------------
    Password:        =88 $Outh D@kota #40
    Password Length: 20 symbol(s)/character(s)
    -------------------------------------------
    The password contains:
     3 white space(s)
     2 symbol(s)
     3 digit(s)
     9 letter(s)
     12 letter(s) or digit(s)
     3 number(s)
     2 punctuation mark(s)
     3 separator character(s)
     7 lowercase letter(s)
     2 uppercase letter(s)
    ===========================================
    Press any key to continue . . .
  5. Press Enter to close the window and return to your programming environment
  6. Execute the application
  7. Type some values as follows:
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:       Roberto
    Middle Name:      Carlos
    Last Name:        Solorio
    ---------------------------------
    Password:         $Outh0D@kota!9
    Confirm Password: $Outh0D@kota!9
  8. Press Enter:
    Account Summary
    ----------------------------
    First Name:      Roberto
    Middle Name:     Carlos
    Last Name:       Solorio
    -------------------------------------------
    Username:        RobertoCarlosSolorio
    Password:        $Outh0D@kota!9
    Password Length: 14 symbol(s)/character(s)
    The password contains:
     1 symbol(s)
     2 digit(s)
     7 lowercase letter(s)
     2 uppercase letter(s)
    ===========================================
    Press any key to continue . . .
  9. Press Enter to close the window and return to your programming environment

The Nullity of a String

A Null String

A string is referred to as null if it doesn't (yet) have a(ny) character(s). This is usually the case when the string has just been created, or a string variable has just been declared. When you have just declared a variable, to indicate that it is null, assign the null keyword to it. The variable must be declared using the string data type, the String class, or the dynamic keyword. Here are example:

public class Exercise
{
    private static void Main()
    {
        string firstName = null;
        dynamic lastName = null;
        string homeAddress = null;
    }
}

If you decide to use the var keyword to declare the variable, you cannot assign null to it.

A Null or Empty String

A string is referred to as null if it has lost its characters. To let you find out whether a string is empty or null, the String class is equipped with a static method named IsNullOrEmpty. Its syntax is:

public static bool IsNullOrEmpty(string value)

A String With a White Space

A string contains a white space if it was previously initialized with at least one character and all of its characters have been removed or the string was simply initialized with something like the Space bar of the keyboard. Here is an example:

string whiteSpace = "    ";

A Null, Empty, or White-Spaced String

To let you find out whether a string is null or contains a white space, the String class is equipped with a static method named IsNullOrWhiteSpace. Its syntax is:

public static bool IsNullOrWhiteSpace(string value)

Strings Comparisons

String Equality

The indexed-equivalent characters of two strings can be compared to know whether one is lower or higher than the other's. If you are only interested to know whether two strings are equivalent, to assist you with that operation, the string class is equipped with a method named Equals. It is overloaded with various versions. Two versions use the following syntaxes:

public override bool Equals(object obj);
public bool Equals(string value);

When calling one of these versions, use an object object or a string value that calls it. The method takes one argument. The variable that calls the method is compared to the value passed as argument. If both values are the exact same, the method returns true. The comparison is performed considering the case of each character. If you don't want to consider the case, use the following version of the method:

public bool Equals(string value, StringComparison comparisonType);

An alternative to the second syntax is to use a static version of this method whose syntax is:

public static bool Equals(string a, string b);

This method takes two string arguments and compares them. If they are the same, the method returns true. This method considers the cases of the characters. If you don't want this factor taken into consideration, use the following version of the method:

public static bool Equals(string a,
			              string b,
    			          StringComparison comparisonType);

Practical LearningPractical Learning: Comparing Strings

  1. Change the document as follows:
    using static System.Console;
    
    namespace PayrollPreparation2
    {
        public class PayrollPreparation
        {
            public static void Main()
            {
                int digits = 0;
                int symbols = 0;
                int letters = 0;
                int numbers = 0;
                int lowercase = 0;
                int uppercase = 0;
                int separators = 0;
                int whiteSpaces = 0;
                int punctuations = 0;
                int letterOrDigits = 0;
    
                WriteLine("Account Creation");
                WriteLine("---------------------------------");
                WriteLine("Provide the following information");
                Write("First Name:       ");
                string strFirstName = ReadLine();
                Write("Middle Name:      ");
                string strMiddleName = ReadLine();
                Write("Last Name:        ");
                string strLastName = ReadLine();
                WriteLine("---------------------------------");
                Write("Password:         ");
                string strNewPassword = ReadLine();
                Write("Confirm Password: ");
                string strConfirmPassword = ReadLine();
    
                Clear();
    
                if (strNewPassword.Equals(strConfirmPassword))
                {
                    int length = strNewPassword.Length;
    
                    for (int i = 0; i < strNewPassword.Length - 1; i++)
                    {
                        if (char.IsWhiteSpace(strNewPassword, i))
                            whiteSpaces++;
                        if (char.IsLetter(strNewPassword, i))
                            letters++;
                        if (char.IsDigit(strNewPassword, i))
                            digits++;
                        if (char.IsLetterOrDigit(strNewPassword, i))
                            letterOrDigits++;
                        if (char.IsNumber(strNewPassword, i))
                            numbers++;
                        if (char.IsPunctuation(strNewPassword, i))
                            punctuations++;
                        if (char.IsSeparator(strNewPassword, i))
                            separators++;
                        if (char.IsSymbol(strNewPassword, i))
                            symbols++;
                        if (char.IsLower(strNewPassword, i))
                            lowercase++;
                        if (char.IsUpper(strNewPassword, i))
                            uppercase++;
                    }
    
                    WriteLine("Account Summary");
                    WriteLine("----------------------------");
                    WriteLine("First Name:      " + strFirstName);
                    WriteLine("Middle Name:     " + strMiddleName);
                    WriteLine("Last Name:       " + strLastName);
                    WriteLine("-------------------------------------------");
                    WriteLine("Password:        " + strNewPassword);
                    WriteLine("Password Length: {0} symbol(s)/character(s)", length.ToString());
                    WriteLine("-------------------------------------------");
                    WriteLine("The password contains:");
                    WriteLine(" " + whiteSpaces + " white space(s)");
                    WriteLine(" " + symbols + " symbol(s)");
                    WriteLine(" " + digits + " digit(s)");
                    WriteLine(" " + letters + " letter(s)");
                    WriteLine(" " + letterOrDigits + " letter(s) or digit(s)");
                    WriteLine(" " + numbers + " number(s)");
                    WriteLine(" " + punctuations + " punctuation mark(s)");
                    WriteLine(" " + separators + " separator character(s)");
                    WriteLine(" " + lowercase + " lowercase letter(s)");
                    WriteLine(" " + uppercase + " uppercase letter(s)");
                    WriteLine("===========================================");
                }
                else
                {
                    WriteLine("The passwords you entered don't match.");
                }
    
                return;
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging:
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:
  3. Type some values are follows:
    Account Creation
    ---------------------------------
    Provide the following information
    First Name:       Andrew
    Middle Name:      Daniel
    Last Name:        Grossman
    ---------------------------------
    Password:         Password1
    Confirm Password: Password#1
  4. Press Enter:
    The passwords you entered don't match.
    Press any key to continue . . .
  5. Press Enter to close to DOS window and return to your programming environment
  6. To start a new application, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
  7. In the middle list, click Empty Project
  8. Change the Name to Chemistry5 and press Enter
  9. To create a new file, on the main menu, click Project -> Add Class...
  10. In the middle list, mahe sure Class is selected.
    Change the Name of the file to Element
  11. Click Add
  12. Complete the Customer.cs file as follows:
    namespace Chemistry5
    {
        public enum Phase
        {
            Gas,
            Liquid,
            Solid,
            Unknown
        }
    
        public class Element
        {
            public string Symbol       { get; set; } = "H";
            public string ElementName  { get; set; } = "Hydrogen";
            public int    AtomicNumber { get; set; } = 1;
            public double AtomicWeight { get; set; } = 1.008;
            public Phase  Phase        { get; set; } = Phase.Gas;
    
            public Element()
            {
            }
    
            public Element(int number)
            {
                AtomicNumber = number;
            }
    
            public Element(string symbol)
            {
                Symbol = symbol;
            }
    
            public Element(int number, string symbol, string name, double mass, Phase phase)
            {
                ElementName  = name;
                AtomicWeight = mass;
                Phase        = phase;
                AtomicNumber = number;
                Symbol       = symbol;
            }
        }
    }
  13. To create a new file, in the Solution Explorer, right-click Chemistry5 -> Add -> Class...
  14. In the middle list, make sure Class is selected.
    Change the Name to Chemistry
  15. Press Enter
  16. Change the class as follows:
    using static System.Console;
    
    namespace Chemistry5
    {
        public class Chemistry
        {
            private static void Describe(Element e)
            {
                WriteLine("Chemistry - " + e.ElementName);
                WriteLine("------------------------");
                WriteLine("Symbol:        " + e.Symbol);
                WriteLine("Element Name:  " + e.ElementName);
                WriteLine("Atomic Number: " + e.AtomicNumber);
                WriteLine("Atomic Weight: " + e.AtomicWeight);
                WriteLine("Phase:         " + e.Phase);
            }
    
            public static int Main()
            {
                Element elm = null;
    
                Element H = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas);
                Element He = new Element(2, "He", "Helium", 4.002602, Phase.Gas);
                Element Li = new Element(3, "Li", "Lithium", 6.94, Phase.Solid);
                Element Be = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid);
                Element B = new Element(5, "B", "Boron", 10.81, Phase.Solid);
                Element C = new Element(number: 6, symbol: "C", name: "Carbon", mass: 12.011, phase: Phase.Solid);
                Element N = new Element(7, "N", "Nitrogen", 14.007, Phase.Gas);
                Element O = new Element(8, "O", "Oxygen", 15.999, Phase.Gas);
                Element F = new Element(9, "F", "Fluorine", 15.999, Phase.Gas);
                Element Ne = new Element("Ne") { AtomicNumber = 10, ElementName = "Neon", AtomicWeight = 20.1797, Phase = Phase.Gas };
                Element Na = new Element(11, "Na", "Sodium", 22.98976928, Phase.Solid);
                Element Mg = new Element(12, "Mg", "Magnesium", 24.305, Phase.Solid);
                Element Al = new Element(13, "Al", "Aluminium", 26.9815385, Phase.Solid);
                Element Si = new Element() { ElementName = "Silicon", AtomicWeight = 28.085, Symbol = "Si", AtomicNumber = 14, Phase = Phase.Solid };
                Element P = new Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998, Symbol = "P", AtomicNumber = 15, Phase = Phase.Solid };
                Element S = new Element(16, "S", "Sulfur", 32.06, Phase.Solid);
                Element Cl = new Element(17, "Cl", "Chlorine", 35.45, Phase.Gas);
                Element Ar = new Element(18, "Ar", "Potassium", 39.792, Phase.Gas);
                Element K = new Element(19, "K", "Potassium", 39.0983, Phase.Solid);
    
                WriteLine("Chemistry - Periodic Table");
                WriteLine("------------------------------------------------");
                Write("Type the chemical symbol of an element you want to review (from H to K): ");
                string answer = ReadLine();
    
                Clear();
    
                switch (answer)
                {
                    case "ar":
                    case "Ar":
                    case "aR":
                    case "AR":
                        elm = Ar;
                        break;
                    case "Al":
                    case "AL":
                    case "aL":
                    case "al":
                        elm = Al;
                        break;
                    case "b":
                    case "B":
                        elm = B;
                        break;
                    case "be":
                    case "Be":
                    case "bE":
                    case "BE":
                        elm = Be;
                        break;
                    case "C":
                    case "c":
                        elm = C;
                        break;
                    case "cl":
                    case "Cl":
                    case "cL":
                    case "CL":
                        elm = Cl;
                        break;
                    default:
                        WriteLine("You must type a valid chemical element symbol.");
                        break;
                    case "F":
                    case "f":
                        elm = F;
                        break;
                    case "h":
                    case "H":
                        elm = H;
                        break;
                    case "he":
                    case "HE":
                    case "He":
                    case "hE":
                        elm = He;
                        break;
                    case "k":
                    case "K":
                        elm = K;
                        break;
                    case "li":
                    case "Li":
                    case "LI":
                    case "lI":
                        elm = Li;
                        break;
                    case "MG":
                    case "mG":
                    case "Mg":
                    case "mg":
                        elm = Mg;
                        break;
                    case "N":
                    case "n":
                        elm = N;
                        break;
                    case "Na":
                    case "na":
                    case "NA":
                    case "nA":
                        elm = Na;
                        break;
                    case "NE":
                    case "ne":
                    case "Ne":
                    case "nE":
                        elm = Ne;
                        break;
                    case "o":
                    case "O":
                        elm = O;
                        break;
                    case "p":
                    case "P":
                        elm = P;
                        break;
                    case "S":
                    case "s":
                        elm = S;
                        break;
                    case "SI":
                    case "Si":
                    case "sI":
                    case "si":
                        elm = Si;
                        break;
                }
    
                Describe(elm);
                WriteLine("================================================");
    
                return 0;
            }
        }
    }
  17. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry - Periodic Table
    ------------------------------------------------
    Type the chemical symbol of an element you want to review (from H to Ar):
  18. When prompted, type K
    Chemistry - Periodic Table
    ------------------------------------------------
    Type the chemical symbol of an element you want to review (from H to Cl): K
  19. Press Enter:
    Chemistry - Potassium
    ------------------------
    Symbol:        K
    Element Name:  Potassium
    Atomic Number: 19
    Atomic Weight: 39.0983
    Phase:         Solid
    ================================================
    Press any key to continue . . .
  20. Press Enter to close the window and return to your programming environment

String Integral Comparison

String comparison consists of examining the characters of two strings with a character of one string compared to a character of the other string with both characters at the same positions. To support this operation, the string class is equipped with the Compare() method that is overloaded with many versions. One of the versions uses the following syntax:

public static int Compare(string String1, string  String2);

This method is declared static and it takes two arguments. The method returns

Here is an example:

public class Exercise
{
    private static void Main()
    {
        string firstName1 = "Andy";
        string lastName1 = "Stanley";
        string firstName2 = "Charles";
        string lastName2 = "Stanley";
        
        int Value1 = string.Compare(firstName1, firstName2);
        int Value2 = string.Compare(firstName2, firstName1);
        int Value3 = string.Compare(lastName1, lastName2);
    }
}

When using this version of the string.Compare() method, the case (upper or lower) of each character is considered. If you don't want to consider this factor, the String class proposes another version of the method. Its syntax is:

public static int Compare(string String1, string String2, bool ignoreCase);

The third argument allows you to ignore the case of the characters when performing the comparison.

String-Case Conversions

Converting a String to Lowercase

To let you convert a string from lowercase to uppercase, the String class is equipped with a method named ToLower. It is overloaded with two versions. One of the versions of this method uses the following syntax:

public string ToLower()

This method considers each character of the string that called it. 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 LearningPractical Learning: Converting a String to Lowercase

  1. Change the Chemistry.cs file as follows:
    using static System.Console;
    
    namespace Chemistry5
    {
        public class Chemistry
        {
            private static void Describe(Element e)
            {
                WriteLine("Chemistry - " + e.ElementName);
                WriteLine("------------------------");
                WriteLine("Symbol:        " + e.Symbol);
                WriteLine("Element Name:  " + e.ElementName);
                WriteLine("Atomic Number: " + e.AtomicNumber);
                WriteLine("Atomic Weight: " + e.AtomicWeight);
                WriteLine("Phase:         " + e.Phase);
            }
    
            public static int Main()
            {
                Element elm = null;
    
                Element H = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas);
                Element He = new Element(2, "He", "Helium", 4.002602, Phase.Gas);
                Element Li = new Element(3, "Li", "Lithium", 6.94, Phase.Solid);
                Element Be = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid);
                Element B = new Element(5, "B", "Boron", 10.81, Phase.Solid);
                Element C = new Element(number: 6, symbol: "C", name: "Carbon", mass: 12.011, phase: Phase.Solid);
                Element N = new Element(7, "N", "Nitrogen", 14.007, Phase.Gas);
                Element O = new Element(8, "O", "Oxygen", 15.999, Phase.Gas);
                Element F = new Element(9, "F", "Fluorine", 15.999, Phase.Gas);
                Element Ne = new Element("Ne") { AtomicNumber = 10, ElementName = "Neon", AtomicWeight = 20.1797, Phase = Phase.Gas };
                Element Na = new Element(11, "Na", "Sodium", 22.98976928, Phase.Solid);
                Element Mg = new Element(12, "Mg", "Magnesium", 24.305, Phase.Solid);
                Element Al = new Element(13, "Al", "Aluminium", 26.9815385, Phase.Solid);
                Element Si = new Element() { ElementName = "Silicon", AtomicWeight = 28.085, Symbol = "Si", AtomicNumber = 14, Phase = Phase.Solid };
                Element P = new Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998, Symbol = "P", AtomicNumber = 15, Phase = Phase.Solid };
                Element S = new Element(16, "S", "Sulfur", 32.06, Phase.Solid);
                Element Cl = new Element(17, "Cl", "Chlorine", 35.45, Phase.Gas);
                Element Ar = new Element(18, "Ar", "Potassium", 39.792, Phase.Gas);
                Element K = new Element(19, "K", "Potassium", 39.0983, Phase.Solid);
                Element Ca = new Element(20, "Ca", "Calcium", 40.078, Phase.Solid);
    
                WriteLine("Chemistry - Periodic Table");
                WriteLine("------------------------------------------------");
                Write("Type the chemical symbol of an element you want to review (from H to Ca): ");
                string answer = ReadLine();
    
                Clear();
    
                switch (answer.ToLower())
                {
                    case "ar":
                        elm = Ar;
                        break;
                    case "al":
                        elm = Al;
                        break;
                    case "b":
                        elm = B;
                        break;
                    case "be":
                        elm = Be;
                        break;
                    case "c":
                        elm = C;
                        break;
                    case "ca":
                        elm = Ca;
                        break;
                    case "cl":
                        elm = Cl;
                        break;
                    default:
                        WriteLine("You must type a valid chemical element symbol.");
                        break;
                    case "f":
                        elm = F;
                        break;
                    case "h":
                        elm = H;
                        break;
                    case "he":
                        elm = He;
                        break;
                    case "k":
                        elm = K;
                        break;
                    case "li":
                        elm = Li;
                        break;
                    case "mg":
                        elm = Mg;
                        break;
                    case "n":
                        elm = N;
                        break;
                    case "na":
                        elm = Na;
                        break;
                    case "ne":
                        elm = Ne;
                        break;
                    case "o":
                        elm = O;
                        break;
                    case "p":
                        elm = P;
                        break;
                    case "s":
                        elm = S;
                        break;
                    case "si":
                        elm = Si;
                        break;
                }
    
                Describe(elm);
                WriteLine("================================================");
    
                return 0;
            }
        }
    }
  2. To exectue the project, on the main menu, click Debug -> Start Without Debugging:
    Chemistry - Periodic Table
    ------------------------------------------------
    Type the chemical symbol of an element you want to review (from H to Ca):
  3. Type a one or two-letter chemical symbol such as CA:
    Chemistry - Periodic Table
    ------------------------------------------------
    Type the chemical symbol of an element you want to review (from H to Ca): CA
  4. Press Enter:
    Chemistry - Calcium
    ------------------------
    Symbol:        Ca
    Element Name:  Calcium
    Atomic Number: 20
    Atomic Weight: 40.078
    Phase:         Solid
    ================================================
    Press any key to continue . . .
  5. Press Enter to close the window and return to your programming environment

Converting a String to Uppercase

To let you convert a string to uppercase, the String class is equipped with a method named ToUpper. This method is overloaded with two versions. The syntax of one of the versions is:

public string ToUpper()

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next