0

How can I remove specific text from a string?

for example I have this string:

string file = "43 , 2000-12-12 003203";

I need to remove the text after the comma, including comma, so I can have as a final result:

string file = "43";

thank you,

n3bi0s
  • 145
  • 2
  • 7
  • 15

3 Answers3

7
string file = "43 , 2000-12-12 003203";
string number = file.Split(',')[0].Trim();
coolmine
  • 4,427
  • 2
  • 33
  • 45
2

You can do this:

string output = file.Substring(0, file.IndexOf(',')).Trim();

However, that might fail if the string doesn't contain a comma. To be safer:

int index = file.IndexOf(',');
string output = index > 0 ? file.Substring(0, index).Trim() : file;

You can also use Split as others have suggested, but this overload would provide better performance, since it stops evaluating the string after the first comma is found:

string output = file.Split(new[] { ',' }, 2)[0].Trim();
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

Possibly by using Split?

file.Split(',')[0].Trim();
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486