August 5, 2008

Useful string methods

//To check a string contains a substring:
bool ContainsString(string container, string contained)
{
  return (container.IndexOf(contained) > -1);
}
// To replace all space characters
mystring.Trim().Replace(" ", string.Empty);
string.Join Opposite To string.Split
private static void TestJoinSplit()
{
    string[] test = new string[] { "x", "y", "z" };
    string joined = string.Join(",", test);
    Debug.WriteLine(joined);
    string[] splitUp = joined.Split(',');
    for (int ix = 0; ix < test.Length; ix++)
    {
        Debug.Assert(splitUp[ix] == test[ix]);
    }
}
Outputs: x,y,z

No comments: