Thursday, August 30, 2012

Unity: Counting substrings inside a string

Tying into the previous post, it seems unity has no actual command for counting the number of instances of a substring in a larger string. I've been hunting around for ages and having found no actual command, I've decided to show some code that does it. The code is about as tight as you can get it without it actually being a command!

As with the last post, I'm using /n instead of \n. This is because when the interpretor looks at \n it decides to ignore the n part, making the search only one character in length. The previous post lists the way you can easily convert /n to \n. I know, it sounds annoying - if I were reading this, I'd think it was annoying. But given that unity gets uppity if you try to enter strings into the inspector (ie, it just wont do line breaks if you do so), you're probably gunna have to end up switching /n to \n anyway. It's just a simple replace command anyway (okay, fine - if you don't want to look at the other post replace is as simple as: guimessage = guimessage.Replace("/n", "\n"); )

But I make excuses like a man! Now, onto the search code!
    var stringtosearch = "this is the test string /n with several /n line breaks in it";
    var searchingfor = "/n";
    var substringspresent=0;
   
    var searchextent=stringtosearch.Length-searchingfor.Length; // makes sure we don't search past the end of the string!
    for (i=0;i<=searchextent;i++)
    {
    var sectionscanned=stringtosearch.Substring(i,searchingfor.Length);
    if (sectionscanned==searchingfor) substringspresent++;
    }
   
    print (substringspresent);

No comments:

Post a Comment