Blog for Junior Developers C#/.NET

Tuesday, October 22, 2024

When creating applications in C#, you will certainly often have to perform various operations related to text. That is, you will want to verify whether the given string contains a string of characters, swap characters, delete, modify text, check the index of the searched character, etc., there are really a lot of possibilities.

In this article, I will present you with 19 string methods that you need to know. Knowing them will certainly be very useful to you in your work when you create applications in C#.

19-most-commonly-used-string-methods-you-should-know.png

Example


In this article, we will work on a simple example.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            Console.ReadLine();
        }
    }
}


Here we have a simple console application and in the Main method initialization of a string variable.


1) IsNullOrWhiteSpace()


The first method is string.IsNullOrWhiteSpace(), which checks if the passed string is null, empty string, or white space. So, if our text is null, empty, string, or white space, we will display a message with the content NULL.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            if (string.IsNullOrWhiteSpace(myString))
            {
                Console.WriteLine("NULL");
            }

            Console.ReadLine();
        }
    }
}


Of course, in our case, because myString has a value assigned, this message will not be displayed after the application is launched. However, if our string was, for example, a space, then this message would be displayed.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " ";

            if (string.IsNullOrWhiteSpace(myString))
            {
                Console.WriteLine("NULL");
            }

            Console.ReadLine();
        }
    }
}


Here the message NULL will be displayed.

Using this method, we can also use negation, i.e. if we want the code to execute if the text is null, empty string, or white space, our code will look like this:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            if (!string.IsNullOrWhiteSpace(myString))
            {
                Console.WriteLine("OK");
            }

            Console.ReadLine();
        }
    }
}


The console will display OK.


2) Split()


The second method will allow us to convert text (string) to a list. This is the Split() method, here we only need to indicate what character separates the given values, and therefore the elements of our new list. We will now create a new list called words and assign to it the words from the myString variable, which are separated by a comma. So we will expect 4 values: Jan, Małgorzata, Kowalski and 1. Then, using a foreach loop, we will display these elements on the console.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            var words = myString.Split(',');

            foreach (var word in words)
                Console.WriteLine(word);

            Console.ReadLine();
        }
    }
}


After starting the application, the actual expected values ​​will be displayed on the screen. Our string has been converted to a list.


3) Join()


The third method is Join(), which is the opposite situation, i.e. converting the list to a string. In this case, we indicate what character these elements should be separated by. Let's assume that we want to create a new string from a previously created list, so that the individual elements are separated by a semicolon.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            var words = myString.Split(',');

            myString = string.Join(';', words);
            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


And this is what the result looks like: " Jan;Małgorzata;Kowalski;1 ".

We have the same result as at the beginning, only this time instead of a comma we separate the words with a semicolon.


4) Trim()


The fourth method, which allows us to remove whitespace from the beginning and end of the string. We can achieve this thanks to the Trim() method. The only important thing is that if we call this method (similarly to other methods that we call on strings) on the previously initialized variable myString, then a new instance of the string is created in the place of the method call and these changes will not be applied to the previously declared variable. If we want to apply these changes to the previously created variable, we have to assign the call of this method to it. Then a new instance will be created, which will be assigned to the variable. So this example will not work correctly:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString.Trim();

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Next, whitespace at the beginning and end of the string will be displayed on the console. For this to work correctly, our example could look like this:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.Trim();

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Now the expected result has been displayed, which is: "Jan,Małgorzata,Kowalski,1".


5) TrimStart()


The fifth method is to remove whitespace, but only from the beginning of the string. For this purpose, we need to use the TrimStart() method.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.TrimStart();

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: "Jan,Małgorzata,Kowalski,1 ";


6) TrimEnd()


The TrimEnd() method will remove all whitespace characters, but from the end of the string.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.TrimEnd();

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: " Jan,Małgorzata,Kowalski,1";


7) ToLower()


The seventh method is the ToLower() method, which allows us to convert all characters to lowercase.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.ToLower();

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: " jan,małgorzata,kowalski,1 ";


8) ToUpper()


We can also do the reverse operation, i.e. convert to uppercase. For this purpose, we will use the ToUpper() method.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.ToUpper();

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: " JAN,MAŁGORZATA,KOWALSKI,1 ";


9) Replace()


The next method is Replace(), which replaces the character that will be passed as the first parameter with the character that is passed as the second parameter. We can replace all commas with semicolons here. This is what the call to this method will look like:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.Replace(',', ';');

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: " Jan;Małgorzata;Kowalski;1 ";


10) IndexOf()


The tenth method IndexOf() allows us to get the index of the searched character in the string. If it is not found, the method will return -1. First, let's check at which index in the string the comma is located.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            var index = myString.IndexOf(',');

            Console.WriteLine(index);

            Console.ReadLine();
        }
    }
}


Result: 4.

In our case the result will be 4 and indeed such an index has a comma (we count from 0).


11) LastIndexOf()


In a similar way we can get the last index of the searched character in the test. For this purpose we will use the LastIndexOf() method. In this example we will also display the index of the last comma in the text:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            var lastIndex = myString.LastIndexOf(',');

            Console.WriteLine(lastIndex);

            Console.ReadLine();
        }
    }
}


Result: 24.


12) Substring()


Method twelve Substring(), which is extracting letters from a string from a given index of a specified length. In our case, we can try to extract the word Małgorzata from the variable myString. Our code can look like this:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.Substring(5, 10);

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: "Małgorzata";


So we start from index 5 and we are interested in 10 characters.


13) Insert()


Another Insert() method, which allows us to add a value to the string in place of the passed index. Let's try to add the value X in the first position, i.e. index zero.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.Insert(0, "X");

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: "X Jan,Małgorzata,Kowalski,1 ";


14) Remove()


Similarly, we can also remove characters from a string. For this purpose, we will use the Remove() method. Here, similarly to before, we first pass the index, and then the number of characters we want to remove.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.Remove(0, 2);

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: "an,Małgorzata,Kowalski,1 ".

In our case, the first two characters were removed.


15) StartsWith()


Thanks to the StartsWith() method, we can check if our string starts with the given value. Also in our case, we will check if the myString variable starts with the character X. The StartsWith() method returns a bool. We can also write the following code for this purpose:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            var startsWithX = myString.StartsWith("X");

            Console.WriteLine(startsWithX);

            Console.ReadLine();
        }
    }
}


Result: False.


16) EndsWith()


In addition to checking what character a string starts with, we can also check what character it ends with. In this case, we can use the EndsWith() method. Let's check if in our case the myString variable ends with the character X.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            var endsWithX = myString.EndsWith("X");

            Console.WriteLine(endsWithX);

            Console.ReadLine();
        }
    }
}


Result: False.


17) Contains()


The Contains() method allows us to check if a string contains a specific string of characters at any position. We will check if our variable contains the text "Jan".

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            var containsJan = myString.Contains("Jan");

            Console.WriteLine(containsJan);

            Console.ReadLine();
        }
    }
}


Result: True.


18) PadLeft()


The PadLeft() method allows us to provide the expected length of the string and if this length is smaller, it will be padded with the passed value on the left side. Let's assume that we want our text to have 30 characters. If it has less, it will be padded with zeros on the left side.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.PadLeft(30, '0');

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: "000 Jan,Małgorzata,Kowalski,1 ".

After this operation, our string has 30 characters. Three zeros have been added to the left.


19) PadRight()


It is similar with the PadRight() method. This time, the letters are completed from the right. This time, we can complete our string with exclamation marks from the right, so that the whole has 35 characters.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var myString = " Jan,Małgorzata,Kowalski,1 ";

            myString = myString.PadRight(35, '!');

            Console.WriteLine(myString);

            Console.ReadLine();
        }
    }
}


Result: " Jan, Małgorzata, Kowalski,1 !!!!!!!!".


SUMMARY


So these are 19 methods that I think are worth knowing. As you can see, the string itself contains many useful methods that you will use many times in your work. Of course, you don't have to learn them by heart, the important thing is to know that they exist, and if you need to use them, then you will look at the documentation.

If you liked this article, be sure to join my community. Sign up for the free newsletter, where every week I share valuable materials, especially regarding C# and the .NET platform (free subscription - newsletter).

//wprowadz kod tutaj (nowa linia shift+enter)
Author of the article:
Kazimierz Szpin

KAZIMIERZ SZPIN
Software Developer C#/.NET, Freelancer. Specializes in ASP.NET Core, ASP.NET MVC, ASP.NET Web API, Blazor, WPF and Windows Forms.
Author of the blog CodeWithKazik.com

Previous article - What is VAR Implicit Type in C#?
Dodaj komentarz
© Copyright 2024 CodeWithKazik.com. All rights reserved. Privacy policy.
Design by Code With Kazik and Modest Programmer.