Link to home
Start Free TrialLog in
Avatar of RosanneParnell
RosanneParnell

asked on

trimming a string in C#

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?
Avatar of mpf1748
mpf1748
Flag of United States of America image

Take a look at the Substring method of String.

HTH,
mpf1748
Avatar of acharbonneau
acharbonneau

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;
s.Substring(...);


In your case, use
s.Substring(0,2)

This returns the first two characters.
ASKER CERTIFIED SOLUTION
Avatar of acharbonneau
acharbonneau

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mohammed Nasman
Hello

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
      MessageBox.Show(s.Substring(0,2));
      // this will delete all the characters  except the first two
      s = s.Remove(s.Length-2,2);
      MessageBox.Show(ss);

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