Chris Ongsuco's Weblog
Information Technology, business, life, food...

String - Left, Right and Mid function

Thursday, July 07, 2005 3:58 AM

public class StringManager
{
      public static string Left(string text, int length)
      {
            return text.Substring(0, length);
      }

      public static string Right(string text, int length)
      {
            return text.Substring(text.Length - length, length);
      }  

      public static string Mid(string text, int start, int end)
      {
            return text.Substring(start, end);
      }  

      public static string Mid(string text, int start)
      {
            return text.Substring(start, text.Length - start);
      }
}


Feedback

# re: String - Left, Right and Mid function

How about this instead?

public static class StringManager
{
public static string Left(string text, int length)
{
return (text.Length < length) ? text : text.Substring(0, length);
}

public static string Right(string text, int length)
{
return (text.Length < length) ? text : text.Substring(text.Length - length, length);
}

public static string Mid(string text, int start, int end)
{
return (text.Length < end + 1) ? text.Substring(start, text.Length-1) : text.Substring(start, end);
}

public static string Mid(string text, int start)
{
return (text.Length < start + 1) ? String.Empty : text.Substring(start, text.Length - start);
}
} 8/4/2005 5:16 PM | Richard Harrison

# re: String - Left, Right and Mid function


Richard,

Nice modification of the code. 8/4/2005 11:17 PM | Chris Ongsuco

# re: String - Left, Right and Mid function

Or you could use the StringUtils class.

http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html
9/15/2008 4:11 AM | Christian

# re: String - Left, Right and Mid function

Great idea!!

Thanks. 4/9/2009 9:36 AM | NL

Post a comment