Tim's Blog
Tim
Life is good Gravatar Joined: Nov 2007
Location: Kalamazoo
Trimming on the front end.

It’s always bothered me that in SQL I can use LEFT or RIGHT to get a specific number of characters for a string but there is nothing so simple in C#. So for a recent project at work and for a recent bug fix in this application I did a little research on it. This is what I’ve found:

public static String Left(string strParam, int iLen)
{
    if (iLen > 0)
    return strParam.Substring(0, iLen);
    else
    return strParam;
}

Usage:

Just by entering your string name, and an integer as the number of characters you would like to see it will truncate your string.

protected void Page_Load(object sender, EventArgs e)
{
    Title = Left("Hello World",7) + "...";
}
public static String Left(String strParam, int iLen)
{
    if (iLen > 0)
    return strParam.Substring(0, iLen);
    else
    return strParam;
}

This would result it your title bar saying “Hello W…” for your page name. This is just an example a better implementation for utilization would be to cut down a long string from a database say perhaps a snippet of a blog posting to display on a front page of a website. 

Happy trimming everyone.

 

Posted by Tim on Jun 5 2008 11:22PM
The Daily WTF:
Because legacy application maintenance is one of the torments found in the outer circles of hell

Infoworld:
23. There is no such thing as a dumb question, so ask it ... once. Then write down the answer so that you don't have to ask it again. If you ask the same person the same question more than twice, you're an idiot (in their eyes).
Source: http://timmeers.net/u/dtryi

Views, feelings and opinions that you see here are my own and not that of my employer and may be different than when originally published, or in some cases differ from day to day.
Kick It!
Filed under: Attachments:

Comments

Anonymous comments are not allowed.
  The Image Store v.5.0.3.20