Did you ever need to do some string manipulation? For example, in a case you have a collection of string and you want to display it nicely in GUI with a separator? Or, if you want to check if a string contains a value? Or just to build your SQL statement in a case you need to create an "IN" clause and you have a collection as a parameter?
String class gives us some powerful helper methods which help us to manipulate our strings. I'm really sure that you already familiar with some of them (like string.Format) and in this post I would like to focus on two major method that maybe help you in your daily work.
(1) string.Join:
In case you want to join a list of strings to one string with a separator, you probably use it.
For example:
In case we have this list
//Join array of strings into one string with seperator
List<string> list = new List<string>() { "a", "b", "c" };
And we want to create this string: "a, b, c", we have two ways:
// (1) The hard way
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.Count(); i++)
{
sb.Append(list[i]);
if (i != list.Count() - 1)
{
sb.Append(",");
}
}
// (2) The easy way
string entireStrings = string.Join(",", list.ToArray());
// (3) And another example in case you have a numeric collection
List<int> numericList = new List<int>() {1, 2, 3};
string entireStrings = string.Join(",",
numericList.Cast<string>().ToArray());
(2) string.IsNullOrEmpty(someString):
We always want to check if a string is equals to null or if string is empty. We have some techniques to implement it like:
bool isValid = line != null && line.Length != 0;
But the most short way is to use string.IsNullOrEmpty(…) method.
For example:
bool isValid = string.IsNullOrEmpty(line);