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
  • 135
  • 2
  • 6
  • 15

3 Answers3

7
string file = "43 , 2000-12-12 003203";
string number = file.Split(',')[0].Trim();
coolmine
  • 4,299
  • 2
  • 32
  • 44
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
  • 141,205
  • 29
  • 278
  • 318
1

Possibly by using Split?

file.Split(',')[0].Trim();
Abe Miessler
  • 79,479
  • 96
  • 291
  • 470