Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[SOLVED] Split string based on a word or single character

Discussion in 'Scripting' started by jshrek, Mar 29, 2015.

  1. jshrek

    jshrek

    Joined:
    Mar 30, 2013
    Posts:
    220
    There seem to be a lot of threads on splitting strings on a single character, but not so many on using a word (multiple characters) to split a string. And the threads I did find were either really old or kind of confusing.

    So I wrote a helper function that will easily do a split string on either a single character or a word and returns an array.

    Code (CSharp):
    1. public string[] splitString(string needle, string haystack) {
    2.     //This will look for NEEDLE in HAYSTACK and return an array of split strings.
    3.     //NOTE: If the returned array has a length of 1 (meaning it only contains
    4.     //        element [0]) then that means NEEDLE was NOT found.
    5.  
    6.     return haystack.Split(new string[] {needle}, System.StringSplitOptions.None);
    7.  
    8. }
    9.  
    10. public void displayArray(string[] array) {
    11.     //Easy way to quickly display all the elements in an array
    12.  
    13.     Debug.Log("Array length: " + array.Length +"\n");
    14.     for (int i=0; i < array.Length; i++) {
    15.         Debug.Log("array[" + i + "] = "+ array[i] +"\n");
    16.     }
    17. }
    18.  
    19. void Start() {
    20.     //Just some test strings to see how splitString works
    21.  
    22.     string[] testSplitArr = splitString(":", "1:2:3");
    23.     displayArray(testSplitArr);
    24.  
    25.     testSplitArr = splitString("hello", "thishelloishelloahellotest");
    26.     displayArray(testSplitArr);
    27.  
    28. }
    Hope this is helpful to somebody!
     
    Bobxan, bvicil and BlipB like this.