In this tutorial, we'll learn about some common string methods in C#.
Equal
This method returns whether the two string objects have the same value or not.
string text = "Dev.to"; string text2 = "Devto"; if(text.Equals(text2)) { Console.Write("Yes!"); } else { Console.Write("No"); } // Outputs - No
Contains
This method returns true
if the given string is present in the source string.
string text = "Dev.to is the best platform for developers"; if(text.Contains("best")) { Console.Write("Yes!"); } else { Console.Write("No"); } // Outputs - Yes!
You can also check if a character is present in the string, for example
text.Contains('b');
Compare
This method compares two strings and returns an integer. It returns
- less than zero if the first substring precedes the second substring in the sort order.
- zero if the two strings are equal
- more than zero if the first substring follows the second substring in the sort order.
string text = "Dev.to"; string text2 = "Devto"; Console.Write(String.Compare(text, text2)); // -1
IndexOf
This method returns the first index of a character or substring in a source string. If the character or substring is not present in the source, it returns -1.
string text = "Dev.to"; Console.WriteLine(text.IndexOf('.')); // 3 Console.WriteLine(text.IndexOf('a')); // -1
IsNullOrEmpty
This method indicates whether the given string is null or an empty string ("").
string text = ""; if(String.IsNullOrEmpty(text)) { Console.Write("Yes"); } else { Console.Write("No"); } // Outputs - Yes
Split
This method splits the string into an array of strings or characters by a delimiter.
string text = "C# provides support for OOP."; foreach (var item in text.Split(' ')) { Console.WriteLine(item); } /* Outputs C# provides support for OOP. */
Join
This method concatenates the elements of the specified array or collection using the given separator.
string[] elements = {"This", "is", "my", "blog."}; Console.Write(String.Join(' ', elements)); // Outputs - This is my blog.
Trim
This method removes all the leading and trailing occurences of the specified character or a set of characters.
string text = "----C# provides support for OOP.----"; Console.Write(text.Trim('-'));
Replace
This method returns a new string after replacing all the occurrences of a specified character or string with another specified character or string.
string text = "C# provides support for OOP."; Console.Write(text.Replace(' ', '_')); // C#_provides_support_for_OOP.
Format
This method is used to convert variables to strings and insert them into another string.
string name = "John"; int age = 32; string text = String.Format("{0} is {1} years old", name, age); Console.Write(text); // John is 32 years old
Top comments (0)