Playing With C# Strings Instance Methods

Introduction

 
Developers love strings. You might not agree with me, but most of the developers I’ve encountered like to play with strings. Now, the focus of this article is to focus more on the instance methods that the String class has. However; before diving into that section of this article, let’s give it a bit of an introduction by answering: “what is a string?”, types of strings, and how to define one.
 

What is a string?

 
In my opinion, we can say that a string is a collection or array-collection of read-only characters.
 
Many of us, think and believe its main use is for storing text values. Furthermore; whenever a string variable is updated, it is being recreated to a new instance.
 
When deciding to create a string, in a strict sense, you can put anything you want, and the compiler won’t complain.
 
Primarily, it starts and ends with either with a single quote or double quote.
 

Types of Strings

 
Basically, there are two types of string in C#.
 
Immutable strings
 
Strings that are once created cannot be modified. Hard to imagine? If you have some experience with strings you, probably questioned yourself: “How did that happen?” Basically, once a string is modified, it returns a new instance of the modified string value.
 
For instance, you have used the “csharp”.ToUpper() method. This method basically returns a new instance of a string that was modified. For that reason, you need to assign the return value to a certain string variable or else you won't get the expected result.
 
Mutable strings – the string content can be modified.
 

Ways to declare a string

 
Basically, we do have many ways to declare a string in our disposable.
 
See the example below, it focuses on declaring a string literal and declaring a string using a constructor. 
  1. [TestMethod]  
  2. public void Test_String_Define_New_String()  
  3. {  
  4.     char[] characterCollection = new char[] { 'i''l','o','v''e','c','s','h','a','r','p' };  
  5.   
  6.     string statement = new string(characterCollection);  
  7.   
  8.     string newStatement = "ilovecsharp";  
  9.   
  10.     Assert.AreEqual(statement, newStatement);  
  11. }  
Another common example of declaring a string is via Console.ReadLine(). However; in our example, I'm using an MSTest project so I decided to mimic the console application inside the MsTest project. 
  1. [TestMethod]  
  2. public void Test_String_Define_New_String_Via_Console_ReadLine()  
  3. {  
  4.     using (var writer = new StringWriter())  
  5.     {  
  6.         Console.SetOut(writer);  
  7.   
  8.         Console.WriteLine("What is your favorite language?");  
  9.   
  10.         using (var reader = new StringReader("C# language"))  
  11.         {  
  12.             Console.SetIn(reader);  
  13.   
  14.             string fromInput = reader.ReadLine();  
  15.   
  16.             Console.WriteLine($"Your favorite programming language is {fromInput}");  
  17.   
  18.             string totalWrite = writer.ToString();  
  19.   
  20.             string assumption = $"What is your favorite language?{Environment.NewLine}Your favorite programming language is {fromInput}{Environment.NewLine}";  
  21.   
  22.             Assert.IsTrue(totalWrite.Equals(assumption));  
  23.         }  
  24.     }  
  25. }  
With the above example, don't be confused, just focus on the reader.ReadLine() method which acts like the Console.ReadLine() which waits for the user's input and processes the input as a new string instance.
 
Another thing to explore, remember that strings are an array of characters. Therefore; we can use an index to get the specific character. Let us see an example below. 
  1. [TestMethod]  
  2. public void Test_String_To_Get_Character_At_Specified_Position()  
  3. {  
  4.     string newCountry = "";  
  5.   
  6.     string country = "Philippines";  
  7.   
  8.     for (int i = 0; i < country.Length; i++)  
  9.     {  
  10.         newCountry += country[i];  
  11.     }  
  12.   
  13.     Assert.AreEqual(newCountry, country);  
  14. }  

C# String instance methods

 
a. CompareTo - this method throws an "ArgumentException" whenever you have supplied the wrong type. One reason is  this method expects a  string type for comparison. Let us see an example below. 
  1. [TestMethod]  
  2. [ExpectedException(typeof(ArgumentException))]  
  3. public void Test_String_CompareTo_Method_Throws_ArgumentException()  
  4. {  
  5.     int birthMonth = 3;  
  6.   
  7.     string statement = "CSharp Rocks";  
  8.   
  9.     statement.CompareTo(birthMonth);  
  10.   
  11.     //throws an argumentexception whenever you are comparting string to non-string type.  
  12. }  
Being aware of the possible exception when this method is misused is nice to know. Let us dig into the usage. Comparing string instance to another string can be done by using this method. Just remember when this method returns zero it means the strings are equal. Let us see an example. 
  1. [TestMethod]  
  2. public void Test_String_CompareTo()  
  3. {  
  4.     string[] programmingLanguages = new string[] { "C""C++""C#""Java""Python"null };  
  5.   
  6.     string favoriteLanguage = "C#";  
  7.   
  8.     foreach (var item in programmingLanguages)  
  9.     {  
  10.         //compares in default settings for string comparison.   
  11.   
  12.         int result = favoriteLanguage.CompareTo(item);  
  13.   
  14.         switch (result)  
  15.         {  
  16.             case -1:  
  17.                 Console.WriteLine($"Is {item} your favorite language?");  
  18.                 break;  
  19.             case 0:  
  20.                 Console.WriteLine("The comparison are equal");  
  21.                 Console.WriteLine($"You got it. My favorite language is {item}");  
  22.                 break;  
  23.             case 1:  
  24.                 Console.WriteLine($"Is {(item == null ? "null" : item)} your favorite language?");  
  25.                 break;  
  26.         }  
  27.   
  28.         Assert.IsTrue((result >= -1 & result <= 1));  
  29.     }  
  30. }  
b. Equals - this methods throws a "NullReferenceException" whenever you have supplied a null instance value for comparison. Let us see an example below. 
  1. [TestMethod]  
  2. [ExpectedException(typeof(NullReferenceException))]  
  3. public void Test_String_Equals_Method_Throws_NullReferenceException()  
  4. {  
  5.     string laptop = null;  
  6.   
  7.     laptop.Equals("DELL");  
  8. }   
So always be careful when checking for equality make sure your string is not null. Let us see how we can get it running properly. 
  1. [TestMethod]  
  2. public void Test_String_Equals_Method()  
  3. {  
  4.     string[] countries = new string[] { "Philippines""PHILIPPINES""philippines""USA""usa""Korea""KOREA" };  
  5.   
  6.     string country = "Philippines";  
  7.   
  8.     foreach (var item in countries)  
  9.     {  
  10.         if (country.Equals(item))     
  11.         {  
  12.             Console.WriteLine($"{item} is equals {country}");  
  13.         }  
  14.         else  
  15.         {  
  16.             if (country.Equals(item, StringComparison.OrdinalIgnoreCase))  
  17.             {  
  18.                 Console.WriteLine($"{item} is equals {country} case being ignored");  
  19.             }  
  20.         }  
  21.     }  
  22. }  
c. ToLower and ToUpper - these methods basically change the cases of your strings which in my opinion is pretty straight forward.
 
Let us see an example below for both of the methods. 
  1. [TestMethod]  
  2. public void Test_String_ToUpper()  
  3. {  
  4.     string statement = "developers like to code people like to talk";  
  5.   
  6.     statement.ToUpper(); //i didn't assign the result to any variable  
  7.   
  8.     foreach (var item in statement.ToCharArray())  
  9.     {  
  10.         if (char.IsLower(item) & !char.IsWhiteSpace(item))  
  11.         {  
  12.             Console.WriteLine($"{item} is not in upper-case");  
  13.             Assert.IsTrue(char.IsLower(item));  
  14.             Assert.IsTrue(!char.IsWhiteSpace(item));  
  15.         }  
  16.     }  
  17.   
  18.     string resultStatementToUpper = statement.ToUpper(); //assigned the result to a variable  
  19.   
  20.     foreach (var item in statement.ToCharArray())  
  21.     {  
  22.         if (char.IsUpper(item) & !char.IsWhiteSpace(item))  
  23.         {  
  24.             Console.WriteLine($"{item} is in upper-case");  
  25.             Assert.IsTrue(char.IsUpper(item));  
  26.             Assert.IsTrue(!char.IsWhiteSpace(item));  
  27.         }  
  28.     }  
  29. }  
  30.   
  31. [TestMethod]  
  32. public void Test_String_ToLower()  
  33. {  
  34.     string statement = "DEVELOPERS LIKE TO CODE PEOPLE LIKE TO TALK";  
  35.   
  36.     statement.ToLower();  
  37.   
  38.     foreach (var item in statement.ToCharArray())  
  39.     {   
  40.         if (char.IsUpper(item) & !char.IsWhiteSpace(item))  
  41.         {  
  42.             Console.WriteLine($"{item} is not in upper-case");  
  43.             Assert.IsTrue(char.IsUpper(item));  
  44.             Assert.IsTrue(!char.IsWhiteSpace(item));  
  45.         }  
  46.     }  
  47.   
  48.     string resultStatementToLower = statement.ToLower();  
  49.   
  50.     foreach (var item in statement.ToCharArray())  
  51.     {  
  52.         if (char.IsLower(item) & !char.IsWhiteSpace(item))  
  53.         {  
  54.             Console.WriteLine($"{item} is in upper-case");  
  55.             Assert.IsTrue(char.IsLower(item));  
  56.             Assert.IsTrue(!char.IsWhiteSpace(item));  
  57.         }  
  58.     }  
  59. }  
Just a few points to mention about the example above. We have use the methods char.IsLower, char.IsUpper.
 
These 2 methods are convenient for the developer to check for the character's current case if lower or upper-case.
 
Lastly, the string method ToCharArray() converts the string literal to its character array representation, wherein you can iterate after getting the array values.
 
d. StartsWith and EndsWith - these methods actually check if the string starts/ends with a certain character. Again, we need to be aware of the exceptions thrown when the methods are misused.
 
Let us see an example below.  
  1. [TestMethod]  
  2. [ExpectedException(typeof(ArgumentNullException))]  
  3. public void Test_String_EndsWith_Throws_ArgumentNullException()  
  4. {  
  5.     string statement = "I didn't end with null";  
  6.   
  7.     statement.EndsWith(null);  
  8. }  
  9.   
  10. [TestMethod]  
  11. [ExpectedException(typeof(ArgumentNullException))]  
  12. public void Test_String_StartsWith_Method_Throws_ArgumentNullException()  
  13. {  
  14.     string myParagraph = "Introduction to C# programmIng.";  
  15.   
  16.     myParagraph.StartsWith(null);  
  17. }  
More examples are below for the usage of the two methods. 
  1. [TestMethod]  
  2. public void Test_String_EndsWith_Using_Default_StringComparison()  
  3. {  
  4.     string[] vowels = new string[] { "a""e""i""o""u" };  
  5.   
  6.     string statement = "I love .NET Framework. How about you";  
  7.   
  8.     foreach (var item in vowels)  
  9.     {  
  10.         var result=  statement.EndsWith(item);  
  11.   
  12.         Assert.IsInstanceOfType(result, typeof(bool));  
  13.     }  
  14. }  
  15.   
  16. [TestMethod]  
  17. public void Test_String_EndsWith_Passing_Different_StringComparison()  
  18. {  
  19.     string[] vowels = new string[] { "a""e""i""o""u" };  
  20.   
  21.     string statement = "I love .NET Framework. How about you".ToUpper();  
  22.   
  23.     foreach (var item in vowels)  
  24.     {  
  25.         var result = statement.EndsWith(item, StringComparison.CurrentCultureIgnoreCase);  
  26.   
  27.         if (result) Console.WriteLine($"Yes it ends with {item}");  
  28.     }  
  29. }  
  30.   
  31. [TestMethod]  
  32. public void Test_String_StartsWith_Method()  
  33. {  
  34.     string myParagraph = "Introduction to C# programmIng.";  
  35.   
  36.     string[] startsWithTheWord = new string[] { "Introduction""introduction" };  
  37.   
  38.     foreach (var word in startsWithTheWord)  
  39.     {  
  40.         var result = myParagraph.StartsWith(word);  
  41.   
  42.         Assert.IsInstanceOfType(result, typeof(bool));  
  43.   
  44.         var resultIgnoredCase = myParagraph.StartsWith(word, StringComparison.OrdinalIgnoreCase);  
  45.   
  46.         Assert.IsInstanceOfType(resultIgnoredCase, typeof(bool));  
  47.     }  
  48. }  
e. TrimStart, TrimEnd, and Trim - the main functionality of these methods is to trim strings. Furthermore, you need to shorten strings where? Is it the head? The tail? Or both? The TrimStart trims the head of the string, the TrimEnd trims the tail of the string and the Trim trims the entire string. Let us see a basic example below. 
  1. [TestMethod]  
  2. public void Test_String_TrimStart()  
  3. {  
  4.     string paragraph = "     Hello World  ";  
  5.   
  6.     string trimTheHead = paragraph.TrimStart();  
  7.     Assert.IsTrue(trimTheHead == "Hello World  ");  
  8.   
  9.     string trimTheTail = paragraph.TrimEnd();  
  10.     Assert.IsTrue(trimTheTail == "     Hello World");  
  11.   
  12.     string trimHeadAndTail = paragraph.Trim();  
  13.     Assert.IsTrue(trimHeadAndTail == "Hello World");  
  14. }  
f. IndexOf and LastIndexOf - The main function of these methods gets the specific position index of the string character. IndexOf focuses on the first instance and LastIndexOf focuses on the last instance of the character inside the string.
 
Again, being a bit defensive doesn't hurt. Let us see the exceptions being thrown by these methods when misused. 
  1. [TestMethod]  
  2. [ExpectedException(typeof(ArgumentOutOfRangeException))]  
  3. public void Test_String_IndexOf_Method_Throws_Argument_Exception()  
  4. {  
  5.     string myParagraph = "Introduction to C# programmIng.";  
  6.   
  7.     int length = myParagraph.Length;  
  8.   
  9.     int index = -1;  
  10.   
  11.     index = myParagraph.IndexOf('a', (length + 1));  
  12. }  
  13.   
  14. [TestMethod]  
  15. [ExpectedException(typeof(ArgumentOutOfRangeException))]  
  16. public void Test_String_LastIndexOf_Method_Throws_Argument_Exception()  
  17. {  
  18.     string myParagraph = "Introduction to C# programmIng.";  
  19.   
  20.     int length = myParagraph.Length;  
  21.   
  22.     int index = -1;  
  23.   
  24.     index = myParagraph.LastIndexOf('I', (length + 1));  
  25. }  
More examples for using both methods. 
  1. [TestMethod]  
  2. public void Test_String_IndexOf_And_LastIndexOf_Method()  
  3. {  
  4.     string[] vowels = new string[] { "a""e""i""o""u" };  
  5.   
  6.     string[] vowelsUpper = new string[] { "A""E""I""O""U" };  
  7.   
  8.     string myParagraph = "Introduction to C# programmIng.";  
  9.   
  10.     int index = -1;  
  11.   
  12.     foreach (var item in vowels)  
  13.     {  
  14.         index = myParagraph.IndexOf(item);  
  15.   
  16.         if (index != -1)  
  17.         {  
  18.             string result = myParagraph.ReplaceIndexWith(index, item.ToUpper());  
  19.   
  20.             Console.WriteLine(result);  
  21.         }  
  22.     }  
  23.   
  24.     foreach (var item in vowelsUpper)  
  25.     {  
  26.         index = myParagraph.LastIndexOf(item);  
  27.   
  28.         if (index != -1)  
  29.         {  
  30.             string result = myParagraph.ReplaceIndexWith(index, item.ToLower());  
  31.   
  32.             Console.WriteLine(result);  
  33.         }  
  34.     }  
  35. }  
A point on the above example. The "ReplaceIndexWith" is an extension method that replaces the index with a new character. More on that later because we are going to discuss the used methods of the "ReplaceIndexWith" which are Insert and Remove methods. 
 
g. Insert and Remove -  These methods help developers to insert and remove characters within a string. These methods are used inside the "ReplaceIndexWith" so let us see the full example below. 
  1. public static string ReplaceIndexWith(this string value, int index, string replacement)  
  2. {  
  3.     string result = value;  
  4.   
  5.     result = value.Insert((index + 1), replacement);  
  6.     result = result.Remove(index, 1);  
  7.   
  8.     return result;  
  9. }  
h. Replace and Contains - These methods do what is says from their method names. Replace actually replaces the string to a new one that you have passed. Contains method checks whether the string contains a specific element. 
  1. [TestMethod]  
  2. public void Test_String_Replace_And_Contains()  
  3. {  
  4.     string[] heroes = new string[] { "Batman""Superman""Robin" };  
  5.   
  6.     foreach (var item in heroes)  
  7.     {  
  8.         if (item.Contains("n"))  
  9.         {  
  10.             string newHeroName = item.Replace("n""x");  
  11.   
  12.             Assert.IsTrue(newHeroName.Contains("x"));  
  13.         }  
  14.     }  
  15. }  
i. Split - This method turns the string into an array of strings, but you need to provide the separator. Let us see an example below.
  1. [TestMethod]  
  2. public void Test_String_Split_Method()  
  3. {  
  4.     string countries = "Philippines,Korea,Japan,Indonesia,Australia";  
  5.   
  6.     var arrayOfCountries = countries.Split(',');  
  7.   
  8.     Assert.IsInstanceOfType(arrayOfCountries, typeof(string[]));  
  9. }  
Remarks
 
We have seen, how we can use the instance methods of string class. 
 
Of course, weren't able to tackle everything but I'm hoping this will help others.
 
I have provided the sample code attached to this article. Or you can download it here from GitHub: https://github.com/jindeveloper/ExploreCSharpStings101
 
That's all, for now, fellow developers.
 
Until  next time, happy programming! 


Similar Articles