C# Strings


In C# a string is a series of Unicode characters. We surround strings with double quotes, whereas we surround characters with single quotes. When we declare a string and then hover our mouse over the keyword string at the beginning of our declaration, we note that the string is of type string, which is a class that is defined in the System namespace.

All primitive types map to a type in the .NET framework. All of these keywords like int, char, bool, string, float and others all map to a type in the .NET framework. The primitive types are all structures. Strings are classes. Chars are primitive types, but string are not.

Consider the Format() method of the string class. Format() is a static method. Since it is static we can use it without creating an object of the string class. We do not need the new keyword, we can just go ahead and use Format() and directly access it with string.Format(). Another example of a static method in C# is Console.WriteLine(). Below is an example of the use of Format(). Format takes parameters; the first placeholder in the first parameter is known as the format string. The first placeholder in the first parameter is {0} and the format string is zero-indexed (starts with zero, not 1). You can also use the Join() method. The first part “,” is the separator. The first line of code below is an example of composite formatting.

string fullName = string.Format("{0} {1}", firstName, lastName);
var myArray = new int[4] {1, 2, 3, 4};
string myNumbers = string.Join (",", myArray);

var myFriends = string[3] {"John", "Jack", "Sally"};
var myFormattedListList = string.Join(",", myFriends);
var myFormattedListListTab = string.Join("\t", myFriends);

Strings are immutable. You cannot change them. There are methods in the string class that allow you to change the strings but they all return a new string. So if we have a string we can return the first letter using an index but we cannot change the string this way. For example if you had string firstNmae = “Mike”; and you wnated the first character you could write char firstChar = firstNmae[0]; We cannot use the assignment operator to change any part of “Mike”.

There are such things as escape characters in C#. A new line is represented as \n. A tab character is \t. A backslash character is \\. A single quotation mark is \’ and \”.

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            string myString = "This is a string. class System.String";
            var myString2 = "Mosh created with type inference";
            String myString3 = "Using the String class in the .NET framework requires: using System;";

            int myInt = 5;     // int is struct System.Int32
            Int32 myInt2 = 7;  // also is struct System.Int32

            var myString4 = myString + " " + myString2;  // + is the concatenation operator

            Console.WriteLine(myString4);

            var firstName = "Mosh";
            var lastName = "Hamedani";
            // the string class has a bunch of static methods, one of which is Format
            var fullName = string.Format("His name is {0} {1}", firstName, lastName);
            Console.WriteLine(fullName);

            Console.ReadKey();
        }
    }
}

Verbatim strings are very useful at times. We just need to prefix the string with the @ sign.

var message = @"Hey there John
go to the following folder
c:\projects\csharp\strings";
Console.WriteLine(message);

A Few Useful String Methods

There are a few useful methods available to you when you are working with strings. There is ToUpper(), ToLower() and Trim(). Of these, I would say Trim() is used the most because it is useful when you are capturing user input and you need to get rid of spaces at the beginning or the end of a string. There is also IndexOf() and LastIndexOf(). There is also Substring() and Replace(). There is IsNullOrEmpty() and IsNullOrWhiteSpace(). We can use Split() to split a string. If you string is a sentence and you want to put all of the words in the string into an array, you can use Split().

Split

We can take a sentence and convert it to a string array with Split(). We specify a separator, which will be a whitespace character (spacebar).

var sentance = "Mosh Hamedani teaches at Udemy.com";
var words = sentance.Split(' ');   // var is a string array
Console.WriteLine(words[0]);
Console.WriteLine(words[1]);
Console.WriteLine(words[2]);
Console.WriteLine(words[3]);
Console.WriteLine(words[4]);
foreach (string word in words){
    Console.WriteLine(word);
}

Converting Strings to Numbers

There are two ways you can convert a string to a number. For example when a user enters a number into a text box, you always get a string, even if the string looks like a number. Using Convert.ToInt32() is probably the preferred way because if the string is null or empty this method returns the default value for integer which is zero. int.Parse() will throw an exception.

string s = "1234";
string d = "12.34";
int i = int.Parse(s);
int j = Convert.ToInt32(s);
decimal k = Convert.ToDecimal(d);
Console.WriteLine(j);
Console.WriteLine(k);

Below are more examples. We can format our numbers as well. We often need to convert numbers to strings when we have output to send out to the console or to our website page.

Converting Numbers to Strings

Notice that the C is a format specifier. There are a few of them: C, D, E, F, X and c, d, e, f and x.

int num = 1234;
string v = num.ToString();  // "1234"
string w = num.ToString("C");  // "$1,234.00"
string x = num.ToString("C0");  // "$1,234"
string y = num.ToString("C4");  // "$1,234.0000"
Console.WriteLine(w);

Here we use both Trim() and ToUpper(). Note that you can reverse the two like this: .ToUpper().Trim().

var fullNameMosh = "Mosh Hamedani ";  // notice the trailing space
Console.WriteLine("Trim: '{0}'", fullNameMosh.Trim());
Console.WriteLine("Trim and ToUpper: '{0}'", fullNameMosh.Trim().ToUpper());