1.4: Strings

In this module we'll study the string type in C#, and we'll learn how to manipulate strings.

Overview

Strings, as briefly mentioned in the previous module, are just a collection of characters that can be stored and used throughout your application in different ways. Along with integers, strings are the most common type of data within programs and that's why you are learning about them first. Strings are the program's representation of text.

File Location

  1. Right click on the solution you made in the first module, go to Add > New Project

  2. Select Console App (.NET Framework)

  3. Name it 0.03_Strings

  4. Write your code for this module within Program.cs of that project

Declaring And Initializing Strings

string firstName; We are declaring or naming a string but not adding any real value to it yet.

string string1 = null; We are initializing a string to null. null is a built in reference in C# that will allow this string to be null or hold nothing. This does not mean 0. 0 is an actual value. This means it has complete absence of value.

string string2 = System.String.Empty; We are initializing a string as empty using System.String.Empty.

string path = "C:\\DotNetProjects\\CSharpFundamentals"; We are initializing a string using a regular string literal using the '\' symbol, an escape literal which hides one of the so it looks normal to the user. (If you only put one you will get an error saying unrecognized escape sequence.)

string path2 = @"C:\DotNetProjects\CSharpFundamentals"; We are initializing a string using a verbatim string literal. The @ lets C# ignore actions of characters like so that it will show up to the user.

var anything = "Strongly typed string"; Var can be used within method bodies that will automatically strongly type to whatever the type should be. Here C# can recognize that it is a string so it stores it as a string.

const string constant1 = "This string will be here foreverrrr"; Constants are variables that cannot be modified. Constants can also be integers, booleans, and null references. Do not use a constant if you expect this value to change in the future.

Visual Representation

    class Program
    {
       // 1      2            3
        string school = "Eleven Fifty";
    }
  1. Data Type

  2. Variable Name

  3. Associated Value

Note: You can have strings that are numbers, but you will not be able to do math with them unless they are converted to an int.

Practice

In your Program.cs in the strings project, practice by typing the following code:

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName;
            string lastName;
            string occupation;

            firstName = "Charlie";
            lastName = "Brown";
            occupation = "Stuntman";

            string fullName = firstName + " " + lastName;

            Console.WriteLine(fullName);

            //String Interpolation
            Console.WriteLine("Name: {0}" + "\n" + "Occupation: {1}", fullName, occupation);
        }
    }
}

String Manipulation

There are a lot of ways to manipulate a string. Here we'll study a few ways to do that.

  1. Concatenation Consider the following code:

    class Program
     {
         static void Main(string[] args)
         {
             string first = "The cars we sell are ";
             string second = "BMW, Lexus, and Mercedes.";
             Console.WriteLine(first + second);
    
             //result: The cars we sell are BMW, Lexus, and Mercedes.
         }
     }

Notice the space after are and before the closing ". If there was no space, you would need to add one, like this:

Console.WriteLine(first + " " + second);

As you can see, with concatenation, we use the + operator to add two strings together.

  1. Composite Formatting:

    class Program
     {
         static void Main(string[] args)
         {
             string firstName = "Nancy";
             string lastName = "St. Stacey";
             Console.WriteLine("Her name is {0} {1}.", firstName, lastName);
    
             //result: Her name is Nancy St. Stacey.
         }
     }
  2. String Interpolation:

    class Program
     {
         static void Main(string[] args)
         {
             string firstName = "Jenn";
             string lastName = "Williams";
             Console.WriteLine($"Her name is {firstName} {lastName}");
    
             //result: Her name is Jenn Williams.
         }
     }
  3. Split You can split up a string into an array of characters in order to manipulate the string. For example, here we take the word typed into the console and make it an array of char's. Then we are able to reverse the word and print it back to the console.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Type a word");
            string word = Console.ReadLine();
            char[] wordArray = word.ToCharArray();
            Array.Reverse(wordArray);
            string reversedWord = new string(wordArray);
            Console.WriteLine(reversedWord);
        }
    }

Next: String Challenges

Last updated