split string before hyphen - asp.net c#

17,037

Solution 1

string result = theString.Substring(0, theString.IndexOf("-")).Trim();

Solution 2

You can use the String Split method:

string[] splitString = string.split('-');

string requiredString = splitString[0];

Solution 3

string s = "10989898 - test1";
string str = s.Substring( 0, s.IndexOf( "-" ) ).Trim();
Share:
17,037
Zerotoinfinity
Author by

Zerotoinfinity

Still Learning

Updated on July 28, 2022

Comments

  • Zerotoinfinity
    Zerotoinfinity almost 2 years

    I have a string :

    10989898 - test1
    

    or another example:

    123178239182 - test2
    

    I need the output like this:

    In first case:

    10989898 
    

    In second case:

    123178239182
    

    means the value before hyphen. How can I do that?

  • Manatherin
    Manatherin over 13 years
    Needs a trim or the result will still have the space at the end
  • JeffK
    JeffK over 13 years
    +1 for remembering to Trim(). Just because you can't see that space doesn't mean it's not there.
  • Manatherin
    Manatherin over 13 years
    This is bad, your creating a throwaway array for no reason
  • Fandango68
    Fandango68 over 2 years
    Meh only a few bytes