The string type represents a character array, and its length is determined by the Length property. All the character positions inside that string are enumerated from 0 to Length-1. C# provides us with many different methods to work with strings and we are going to examine ones that are used most of the time.

To download a source code, you can visit our Work With Strings Source Code repository.

For the complete navigation of this series check out: C# Back to Basics.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

We will learn about the following topics:

So, let’s start.

Substring, IndexOf, LastIndexOf String Methods in C#

Substring(int startIndex) is the method that returns part of the string from startIndex to the end of the string.

Substring(int startIndex, int length) is the method that returns part of the string with a defined length from the startIndex.

Let’s see this in practice:

class Program
{
    static void Main(string[] args)
    {
        string testString = "this is some string to use it for our example.";

        string partWithoutLength = testString.Substring(10);
        string partWithLength = testString.Substring(5, 10);

        Console.WriteLine(partWithoutLength);
        Console.WriteLine(partWithLength);

        Console.ReadKey();
    }
}

IndexOf() is the method that returns the integer value position of the first appearance of the character, or a string in the selected string. If that value doesn’t exist, the method will return -1.

There are different overloads of this method: IndexOf(char value), IndexOf(string value), IndexOf(char value, int startIndex), IndexOf(string value, int startIndex) etc. If we use this method with the startIndex parameter, we will not search from the beginning of the string but from that position to the end:

int charPosition = testString.IndexOf('i');
int stringPosition = testString.IndexOf("some");
int charPosWithStartIndex = testString.IndexOf('s', 10);
int stringPosWithStartIndex = testString.IndexOf("some", 10);

LastIndexOf() is the method that returns the position of the last appearance of a character or a string value. This method has the same overloads as the IndexOf method:

int lastPosition = testString.LastIndexOf('o');
int stringLastPosition = testString.LastIndexOf("is");

Contains, StartsWith, EndsWith

Contains(string value) is the method that returns true if a string contains the value, otherwise, it will return false:

bool containsResult = testString.Contains("for");

StartsWith(string value) is the method that returns true if a string starts with the value, otherwise, returns false. As opposed to this method the EndsWith(string value) method returns true if a string ends with the value, otherwise, returns false:

bool startsWithResult = testString.StartsWith("bad");
bool endsWithResult = testString.EndsWith("example");

Remove, Insert

Remove(int startIndex) method removes characters from the string from the startIndex position to the end of the string and returns that new string. There is an overloaded method Remove(int startIndex, int count) which removes a specified number of characters from the string from the starting index position. With the count parameter we decide how many characters we want to delete:

string loweredString = testString.Remove(10);
string loweredStringWithCount = testString.Remove(10, 9);

Insert(int startIndex, string value) is the method that inserts the value into the string from the startIndex position and returns a modified string:

string stringWithInsert = testString.Insert(13, "UPDATED ");

ToLower, ToUpper

ToLower() returns a new string with all the lower case letters:

string lowerCaseString = testString.ToLower();

ToUpper() returns a new string with all the upper case letters:

string upperCaseString = testString.ToUpper();

Examples of Using String Methods in C#

Example 1: Create an application that accepts the name and last name, space-separated, as input, and then prints out the name in one row and last name in another row:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your full name, blank space separated");
        string fullName = Console.ReadLine();

        int blankPosition = fullName.IndexOf(' ');
        string name = fullName.Substring(0, blankPosition);
        string lastName = fullName.Substring(blankPosition + 1);

        Console.WriteLine(name);
        Console.WriteLine(lastName);

        Console.ReadKey();
    }
}

Example 2: Create an application that accepts as input a sentence and removes the first and last word of that sentence:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your sentence: ");

        string sentence = Console.ReadLine();

        int firstBlankPosition = sentence.IndexOf(' ');
            
        string withoutFirstWord = sentence.Remove(0, firstBlankPosition + 1);

        int lastBlankPosition = withoutFirstWord.LastIndexOf(' ');

        string withoutFirstAndLast = withoutFirstWord.Remove(lastBlankPosition);

        Console.WriteLine(withoutFirstAndLast);

        Console.ReadKey();
    }
}

This is the result:

Enter your sentence:
This is a new sentence with several words.
is a new sentence with several

Conclusion

We have mastered the usage of the most used string methods in C#. With the combination of these methods, we can create powerful solutions for our applications.

Stay with us in the next post, where we are talking about Conditions in C#.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!