Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

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);

Unity: Getting new line in inspector entered strings to work

It's weird - in a script I had some text defined with \n to create a new line and that worked out.

But when I defined an array of strings and filled them in in the inspector, it'd just show the \n instead of creating a new line!

So here's a solution:
guimessage = guimessage.Replace("/n", "\n");
 In your strings, have /n instead of \n. It'll replace them and for some reason, they then start working! It puts the special magic back in!