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)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
{
    public static int Main(string[] args)
    {
        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.

Practical LearningPractical Learning: Introducing Strings

  1. Start Microsoft Visual Studio and create a Windows Forms application named HumanResources1
  2. Design the form as follows:

    Introducing Strings

    Control (Name) Text
    GroupBox   Employee Information
    Label   Employee #:
    TextBox txtEmployeeNumber  
    Label   Hourly Salary:
    TextBox txtHourlySalary  
    Label   Employee Name:
    TextBox txtEmployeeName  
  3. On the form, click the Employee # text box
  4. In the Properties window, click the Events button Events
  5. Double-click Leave

A Null or Empty String

A string is referred to as null if it has lost its character(s). 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)

Practical LearningPractical Learning: Using a Null String

  1. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace HumanResources1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void txtEmployeeNumber_Leave(object sender, EventArgs e)
            {
                int[]    employeesNumbers    = new int[]    { 293708, 594179, 820392, 492804, 847594 };
                string[] employeesFirstNames = new string[] { "Christine", "Peter", "Jonathan", "Lilly", "Gabriel" };
                string[] employeesLastNames  = new string[] { "Greenberg", "Keys", "Verland", "Malone", "Reasons" };
                double[] hourlySalaries      = new double[] { 22.86, 29.47, 30.72, 18.39, 17.38 };
    
                if (string.IsNullOrEmpty(txtEmployeeNumber.Text))
                {
                    MessageBox.Show("You must enter an employee's number", "Payroll Preparation");
                    return;
                }
    
                int emplNbr = int.Parse(txtEmployeeNumber.Text);
    
                for(int nbr = 0; nbr <= employeesNumbers.Length - 1; nbr++)
                {
                    if(emplNbr == employeesNumbers[nbr])
                    {
                        txtEmployeeName.Text = employeesLastNames[nbr] + ", " + employeesFirstNames[nbr];
                        txtHourlySalary.Text = hourlySalaries[nbr].ToString();
                    }
                }
            }
        }
    }
  2. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging:

    Introduction to the Nullity of a String

  3. In the Employee # text box, type 293708

    A Null or Empty String

  4. Press Tab

    A Null or Empty String

  5. Close the form and return to your programming environment
  6. Start Microsoft Visual Studio and create Windows Forms application named AccountValidation2
  7. Design the form as follows:

    Doing Something While a Condition is True

    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  
  8. On the form, click the New Password text box
  9. In the Properties window, click the Events button Events
  10. Double-click Leave

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)

Practical LearningPractical Learning: Checking a Text-Based Control

  1. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace AccountValidation2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void txtNewPassword_Leave(object sender, EventArgs e)
            {
                string strNewPassword = txtNewPassword.Text;
                int digits = 0, symbols = 0, lowercase = 0, uppercase = 0;
                int length = strNewPassword.Length;
    
                if (string.IsNullOrWhiteSpace(txtNewPassword.Text))
                {
                    MessageBox.Show("You cannot have an empty password. You must create " +
                                    "a new password that conforms to this company's password rules.",
                                    "Account Validation");
                    return;
                }
    
                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();
            }
        }
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. Click the New Password text box and press Tab:

    Modeling a Window

  4. Click OK on the message box
  5. Close the form and return to your programming environment

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);

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 (and therefore the string data type) is equipped with a method named Compare(), That method 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 are three examples of calling this method:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        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);

        WriteLine("=============================================");
        WriteLine("\"{0}\"    compared to \"{1}\" produces {2}", firstName1, firstName2, Value1);
        WriteLine("\"{0}\" compared to \"{1}\"    produces  {2}", firstName2, firstName1, Value2);
        WriteLine("\"{0}\" compared to \"{1}\" produces  {2}", lastName1, lastName2, Value3);
        WriteLine("=============================================");
        return 2;
    }
}

This would produce:

=============================================
"Andy"    compared to "Charles" produces -1
"Charles" compared to "Andy"    produces  1
"Stanley" compared to "Stanley" produces  0
=============================================
Press any key to continue . . .

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.

Practical LearningPractical Learning: Integrally Comparing Strings

  1. Click Form1.cs [Design] to access the form
  2. On the form, click the Confirm Password text box
  3. In the Events section of the Properties window, double-click Leave
  4. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace AccountValidation2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void txtNewPassword_Leave(object sender, EventArgs e)
            {
                string strNewPassword = txtNewPassword.Text;
                int digits = 0, symbols = 0, lowercase = 0, uppercase = 0;
                int length = strNewPassword.Length;
    
                if (string.IsNullOrWhiteSpace(txtNewPassword.Text))
                {
                    MessageBox.Show("You cannot have an empty password. You must create " +
                                    "a new password that conforms to this company's password rules.",
                                    "Account Validation");
                    return;
                }
    
                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();
            }
    
            private void txtConfirmPassword_Leave(object sender, EventArgs e)
            {
                if (string.IsNullOrWhiteSpace(txtConfirmPassword.Text))
                {
                    MessageBox.Show("You must type the same password in the Confirm Password text box.",
                                    "Account Validation");
                    return;
                }
    
                if (string.Compare(txtNewPassword.Text, txtConfirmPassword.Text) == 0)
                    MessageBox.Show("Your password will be saved successfully.", "Account Validation");
                else
                    MessageBox.Show("The passwords don't match.", "Account Validation");
            }
        }
    }
  5. To execute the application, on the main menu, click Debug -> Start Without Debugging
  6. In the New Password text box, type something, such as $outhD@KoTA1889 and press Tab:

    Integrally Comparing Strings

  7. In the Confirm Password text box, type something different, such as $0uthD@koTA1889 and press Tab

    Integrally Comparing Strings

  8. Type the same passwords in both text boxes
  9. Close the form and return to your programming environment
  10. Start a new Windows Forms application named Chemistry10
  11. In the Solution Explorer, right-click Chemistry10-> Add -> Class
  12. Type the name of the file as Element
  13. Click Add
  14. Populate the document as follows:
    namespace Chemistry10
    {
        public enum Phase { Gas, Liquid, Solid, Unknown }
    
        public class Element
        {
            public string Symbol       { get; set; }
            public string ElementName  { get; set; }
            public int    AtomicNumber { get; set; }
            public double AtomicWeight { get; set; }
            public Phase  Phase        { get; set; }
    
            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;
                Symbol = symbol;
                AtomicNumber = number;
            }
        }
    }
  15. In the Solution Explorer, double-click Form1.cs
  16. Design the form as follows:

    String-Case Conversions

    Control (Name) Text
    Label   Enter Chemical Symbol:
    TextBox txtEntered
    GroupBox   Element Detais
    Label   Atomic Number:
    TextBox txtAtomicNumber
    Label   Symbol:
    TextBox txtSymbol
    Label   Element Name:
    TextBox txtElementName
    Label   Atomic Weight:
    TextBox txtAtomicWeight
    Label   Phase:
    TextBox txtPhase
  17. In the Properties window, click the Events button Events
  18. On the form, click the Enter Chemical Symbol text box
  19. In the Properties window, double-click Leave

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. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Chemistry10
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            Element IdentifyElement(string identifier)
            {
                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(name: "Carbon", mass: 12.011, symbol: "C", number: 6, phase: Phase.Solid);
                Element N  = new Element(7)    { Symbol = "N", AtomicWeight = 14.007, ElementName = "Nitrogen", Phase = Phase.Gas };
                Element O  = new Element("O")  { AtomicNumber = 8, ElementName = "Oxygen", AtomicWeight = 15.999, Phase = Phase.Gas };
                Element F  = new Element("F")  { AtomicNumber = 9, ElementName = "Fluorine", AtomicWeight = 15.999, Phase = 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() { AtomicWeight = 35.446, Symbol = "Cl", ElementName = "Chlorine", AtomicNumber = 17, Phase = Phase.Gas };
                Element Ar = new Element() { ElementName = "Argon", AtomicWeight = 39.792, Symbol = "Ar", AtomicNumber = 18, Phase = Phase.Gas };
                Element K  = new Element() { ElementName = "Potassium", Symbol = "K", Phase = Phase.Solid, AtomicWeight = 39.0983, AtomicNumber = 19 };
                Element Ca = new Element() { Symbol = "Ca", Phase = Phase.Solid, AtomicNumber = 20, ElementName = "Calcium", AtomicWeight = 40.078 };
                Element Sc = new Element() { AtomicNumber = 21, Symbol = "Sc", AtomicWeight = 44.9559085, Phase = Phase.Solid, ElementName = "Scandium" };
                Element Ti = new Element() { ElementName = "Titanium", AtomicWeight = 47.8671, Symbol = "Ti", AtomicNumber = 22, Phase = Phase.Solid };
                Element V  = new Element() { AtomicWeight = 50.9415, Phase = Phase.Solid, AtomicNumber = 23, ElementName = "Vanadium", Symbol = "V" };
                Element Cr = new Element() { AtomicNumber = 24, Symbol = "Cr", AtomicWeight = 51.9961, Phase = Phase.Solid, ElementName = "Chromium" };
    
                Element selected = new Element();
    
                switch (identifier)
                {
                    default:
                        selected = new Element(0, "", "Known", 0.00, Phase.Unknown); ;
                        break;
                    case "k":
                        selected = K;
                        break;
                    case "cr":
                        selected = Cr;
                        break;
                    case "he":
                        selected = He;
                        break;
                    case "be":
                        selected = Be;
                        break;
                    case "ca":
                        selected = Ca;
                        break;
                    case "li":
                        selected = Li;
                        break;
                    case "b":
                        selected = B;
                        break;
                    case "c":
                        selected = C;
                        break;
                    case "n":
                        selected = N;
                        break;
                    case "o":
                        selected = O;
                        break;
                    case "sc":
                        selected = Sc;
                        break;
                    case "h":
                        selected = H;
                        break;
                    case "ti":
                        selected = Ti;
                        break;
                    case "f":
                        selected = F;
                        break;
                    case "ne":
                        selected = Ne;
                        break;
                    case null:
                        selected = new Element(0, "", "Known", 0.00, Phase.Unknown); ;
                        break;
                    case "na":
                        selected = Na;
                        break;
                    case "v":
                        selected = V;
                        break;
                    case "mg":
                        selected = Mg;
                        break;
                    case "al":
                        selected = Al;
                        break;
                    case "p":
                        selected = P;
                        break;
                    case "s":
                        selected = S;
                        break;
                    case "cl":
                        selected = Cl;
                        break;
                    case "ar":
                        selected = Ar;
                        break;
                    case "si":
                        selected = Si;
                        break;
                }
    
                return selected;
            }
    
            void Show(Element ce)
            {
                txtSymbol.Text = ce.Symbol;
                txtAtomicNumber.Text = ce.AtomicNumber.ToString();
                txtElementName.Text = ce.ElementName;
                txtAtomicWeight.Text = ce.AtomicWeight.ToString();
                txtPhase.Text = ce.Phase.ToString();
            }
    
            private void txtEntered_Leave(object sender, EventArgs e)
            {
                string strSelected = txtEntered.Text;
    
                string converted = strSelected.ToLower();
    
                Element elm = IdentifyElement(converted);
    
                Show(elm);
    
                /* Notice that the previous 4 lines can be simplified as follows:
                 * 
                Show(IdentifyElement(txtEntered.Text.ToLower()));
                 *
                 **/
            }
        }
    }
  2. To exectue the project, on the main menu, click Debug -> Start Without Debugging

    Converting a String to Lowercase

  3. In the Enter Chemical Symbol dialog box, type a one or two-letter chemical symbol, such as CR

    Converting a String to Lowercase

  4. Press Tab:

    Converting a String to Lowercase

  5. Close the form 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()

Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        string strFullName = "Alexander Patrick Katts";
        string strUppercase = strFullName.ToUpper();

        WriteLine("======================================");
        WriteLine("Full Name:    {0}", strFullName);
        WriteLine("In Uppercase: {0}", strUppercase);
        WriteLine("======================================");
        return 2;
    }
}

This would produce:

======================================
Full Name:    Alexander Patrick Katts
In Uppercase: ALEXANDER PATRICK KATTS
======================================
Press any key to continue . . .

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2021, FunctionX Next