Get everything after first occurence of a given string

I’m trying to cut away some parts of a URL for future processing. I just can’t make it happen. I’ve crafted a demo to directly recreate the problem:

        string outcome;
        outcome = @"Scripts\System\Renderer.cs";
        outcome = outcome?.Substring(outcome.IndexOf("Scripts", StringComparison.Ordinal));//.Split('\\').First();
        Debug.Log(outcome);        // rer.cs

Console says rer.cs, whaaaaaaaa? Shouldn’t it say “Renderer.cs”?

What I’m trying to do is return part of a string, that is after the first occurrence of “Scripts”, as such:

C:\one\two\Assets\Scripts\Master\Registry.cs                // Master\Registry.cs
C:\tango\zulu\Assets\Scripts\Something\Item\Yep\Search.cs   // Something\Item\Yep\Search.cs
C:\Scripts\ohno.cs                                          // ohno.cs

I have this:
outcome = outcome?.Substring(outcome.IndexOf("Scripts\\", StringComparison.Ordinal)).TrimStart('/');;//.Split('\\').First();

But that’s too long, there has to be a shorter way to do it with a single method. I’m pretty sure it’s bad performing as well.

Use Substring

        string outcome;
        outcome = @"Scripts\System\Renderer.cs";
            int scriptsIndex = outcome.IndexOf(@"Scripts\", StringComparison.OrdinalIgnoreCase);
         
            // -1 if not found
            if(scriptsIndex >= 0){
                int scriptsIndexEnd = scriptsIndex + 8; // 8 = length of "Scripts\"
                int stringLength = outcome.Length - scriptsIndexEnd;
                outcome = outcome.Substring(scriptsIndexEnd, stringLength);
                Console.WriteLine(outcome );
            }
1 Like

Fantastic. Thank you. Exactly what I was looking for.

1 Like