Determine whether a string ends with another string in C#
This post will discuss how to determine whether a string ends with another string in C#.
1. Using String.EndsWith() method
The standard method to determine whether a string ends with another string is to use the String.EndsWith() method. It returns true if the end of the string matches with the specified string. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string str = "100$"; string suffix = "$"; bool endsWith = str.EndsWith(suffix); Console.WriteLine(endsWith); // True } } |
2. Using Enumerable.Any() method
If you need to match the end of a string with the list of given strings, consider using LINQ’s Enumerable.Any() method. It returns true when any element of a sequence satisfy the specified condition. The following code example shows how to test a suffix in a list of strings using the Any() and EndsWith() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; public class Example { public static void Main() { string[] extensions = { ".txt", ".log", ".bat", ".sh" }; string str = "system.log"; bool endsWith = extensions.Any(suffix => str.EndsWith(suffix)); Console.WriteLine(endsWith); // True } } |
3. Using Regex.IsMatch() method
Alternatively, you can use the regular expression to match the end of a string with the list of strings. This can be done using the Regex.IsMatch() method, which tells whether the specified string matches the provided regex. This is demonstrated below. Note that $ matches with the end of the string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string str = "system.log"; bool endsWith = Regex.IsMatch(str, "(txt|log|bat|sh)$"); Console.WriteLine(endsWith); // True } } |
That’s all about determining whether a string ends with another string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)