Cassie Kasandr
Cassie Kasandr

Reputation: 341

Remove a word and everything after

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#?

Upvotes: 5

Views: 18195

Answers (4)

Selman Genç
Selman Genç

Reputation: 101681

Simply use IndexOf and Substring methods:

int index = str.IndexOf("steam.exe");  
string result = str.Substring(0, index);

Upvotes: 17

Snickbrack
Snickbrack

Reputation: 956

...
string str_ = "123\123"
string str_splitted = str_.split(@"\")[0];
...

EDIT: here is my explanation:

The split-Function for strings is in my opinion the simpliest solution to get to your wanted results. Because of the fact that you can specify a particular char to split your string at this position.

You always keep the full control of the process ;)

Upvotes: -3

Tim Schmelter
Tim Schmelter

Reputation: 460058

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.

Upvotes: 13

DMAN
DMAN

Reputation: 471

Use System.IO.Path:

Path.GetDirectoryName(filepath)

which will return "C:\Program Files (x86)\Steam"

Upvotes: 2

Related Questions