4b0
4b0

Reputation: 22323

Grab a part of text when it matches, get rid of the rest because it's useless

I have a text called

string path = "Default/abc/cde/css/";

I want to compare a text.

string compare = "abc";

I want a result

string result = "Default/abc";

The rest of the path /cde/css is useless.Is it possible to grab the desire result in asp.net c#. Thanks.

Upvotes: 2

Views: 74

Answers (4)

ojlovecd
ojlovecd

Reputation: 4902

I suggest that if you meet questions of this kind in the future, you should try it yourself first.

string result = path.Contains(compare) ? path.Substring(0, (path.IndexOf(compare) + compare.Length)) : path;

Upvotes: 0

Curtis
Curtis

Reputation: 103388

Try this. This will loop through the different levels (assuming these are directory levels) until it matches the compare, and then exit the loop. This means that if there is a folder called abcd, this won't end the loop.

string path = "Default/abc/cde/css";
string compare = "abc";
string result = string.Empty;
foreach (string lvl in path.Split("/")) {
    result += lvl + "/";
    if (lvl == compare)
    {
        break;
    }
}
if (result.Length>0)
{
   result = result.substring(0, result.length-1);
}

Upvotes: 1

Renatas M.
Renatas M.

Reputation: 11820

Is this what you looking for?:

string result = path.Substring(0, path.IndexOf(compare)+compare.Length);

Upvotes: 1

Kevin Holditch
Kevin Holditch

Reputation: 5303

string path = "Default/abc/cde/css/";
string answer = "";
string compare = "abc";

if (path.Contains(compare ))
{
     answer = path.Substring(0, path.IndexOf(stringToMatch) + compare.Length);
}

Something like the above should work.

Upvotes: 0

Related Questions