Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Get everything after first occurence of a given string

Discussion in 'Scripting' started by qcw27710, Dec 5, 2019.

  1. qcw27710

    qcw27710

    Joined:
    Jul 9, 2019
    Posts:
    139
    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:
    Code (CSharp):
    1.         string outcome;
    2.         outcome = @"Scripts\System\Renderer.cs";
    3.         outcome = outcome?.Substring(outcome.IndexOf("Scripts", StringComparison.Ordinal));//.Split('\\').First();
    4.         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:
    Code (CSharp):
    1. C:\one\two\Assets\Scripts\Master\Registry.cs                // Master\Registry.cs
    2. C:\tango\zulu\Assets\Scripts\Something\Item\Yep\Search.cs   // Something\Item\Yep\Search.cs
    3. 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.
     
    Last edited: Dec 5, 2019
  2. ZO5KmUG6R

    ZO5KmUG6R

    Joined:
    Jul 15, 2010
    Posts:
    490
    Use Substring

    Code (CSharp):
    1.         string outcome;
    2.         outcome = @"Scripts\System\Renderer.cs";
    3.             int scriptsIndex = outcome.IndexOf(@"Scripts\", StringComparison.OrdinalIgnoreCase);
    4.          
    5.             // -1 if not found
    6.             if(scriptsIndex >= 0){
    7.                 int scriptsIndexEnd = scriptsIndex + 8; // 8 = length of "Scripts\"
    8.                 int stringLength = outcome.Length - scriptsIndexEnd;
    9.                 outcome = outcome.Substring(scriptsIndexEnd, stringLength);
    10.                 Console.WriteLine(outcome );
    11.             }
     
    qcw27710 likes this.
  3. qcw27710

    qcw27710

    Joined:
    Jul 9, 2019
    Posts:
    139
    Fantastic. Thank you. Exactly what I was looking for.
     
    ZO5KmUG6R likes this.