Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a word and everything after

Tags:

string

c#

Let's say I have a string:

"C:\Program Files (x86)\Steam\steam.exe /lets go 342131 some random text"

And I want to remove from that string the 'steam.exe' and everything that follows after that. So my trimmed string would look like:

"C:\Program Files (x86)\Steam\"

How can I do that in C#?

like image 827
Cassie Kasandr Avatar asked Nov 30 '22 11:11

Cassie Kasandr


2 Answers

Simply use IndexOf and Substring methods:

int index = str.IndexOf("steam.exe");  
string result = str.Substring(0, index);
like image 57
Selman Genç Avatar answered Dec 10 '22 06:12

Selman Genç


If you want to remove something from the end of a string use String.Remove:

int indexOfSteam = text.IndexOf("steam.exe");
if(indexOfSteam >= 0)
    text = text.Remove(indexOfSteam);

It's the same as text.Substring(0, indexOfSteam). It just makes the intention clearer.

like image 30
Tim Schmelter Avatar answered Dec 10 '22 07:12

Tim Schmelter