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);
      }
}



  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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

# re: String - Left, Right and Mid function

JAVA is case sensitive programming languange !!!

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);
}
} 5/25/2011 1:59 AM | Pefo

# re: String - Left, Right and Mid function

it should better be :

public static string Left(string text, int length)
{
return text.Substring(0, text.length()>length?length:text.length());
} 6/8/2011 4:06 PM | Berkhan

Post a comment