Showing posts with label c# strings. Show all posts
Showing posts with label c# strings. Show all posts

February 22, 2011

String Class Extensions

string.Right() method and case insensisitive IndexOf
String Extension Collection for C#
Favorite String Extension Methods in C#

Convert 'string.Right()' to an extension method
static class StringExtensions
{
  static string Right(this string s, int count )
  {
    string newString = String.Empty;
    if (s != null && count > 0)
    {
      int startIndex = s.Length - count;
      if (startIndex > 0)
        newString = s.Substring( startIndex, count );
      else
        newString = s;
    }
    return newString;
  }
}

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

September 23, 2007

Test String Padding Functions

private static void TestPadding()
{
int ix = 0;
string result = string.Empty;
result = ix.ToString("X");
result = result.PadLeft(8, '0');
System.Diagnostics.Debug.Assert(result.Length == 8);
ix = 1;
result = ix.ToString("X");
result = result.PadLeft(8, '0');
System.Diagnostics.Debug.Assert(result.Length == 8);
ix = 9999;
result = ix.ToString("X");
result = result.PadLeft(8, '0');
System.Diagnostics.Debug.Assert(result.Length == 8);
ix = 99999999;
result = ix.ToString("X");
result = result.PadLeft(8, '0');
System.Diagnostics.Debug.Assert(result.Length == 8);
ix = int.MaxValue;
result = ix.ToString("X");
result = result.PadLeft(8, '0');
System.Diagnostics.Debug.Assert(result.Length == 8);
ix = int.MinValue;
result = ix.ToString("X");
result = result.PadLeft(8, '0');
System.Diagnostics.Debug.Assert(result.Length == 8);
}