trimming a string in C#

Posted on 2004-11-18
Last Modified: 2010-04-15
I have a variable containing "MS33" as its contents. I want to trim the variable to only the first 2 characters. Result="MS". What function will do this for me?
Question by:RosanneParnell
    LVL 3

    Expert Comment

    Take a look at the Substring method of String.

    LVL 2

    Expert Comment

    Substring is the right method, but note that it's not static.
    You can't call String.Substring(...)
    You need to first create an instance of a string, then call the method from the object variable.

    String s;

    In your case, use

    This returns the first two characters.
    LVL 2

    Accepted Solution

    oops...need to initialize it also:

    String s;
    s = "MS33"
    s.Substring(...);  //returns "MS"
    LVL 22

    Expert Comment


    If you would like just to return first two characters use Substring

    but if you would like to trim the variable to contian only the first two characters use Remove method

          string s = "MS33";
          // this will return the first two characters without effect the variable
          // this will delete all the characters  except the first two
          s = s.Remove(s.Length-2,2);

    LVL 2

    Expert Comment

    You could use trim('3') or trim("3")

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Article by: Najam
    Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
    This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
    This video discusses moving either the default database or any database to a new volume.
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now