Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Splitting a string on new lines

Discussion in 'Scripting' started by Studio_AKIBA, Jan 15, 2017.

  1. Studio_AKIBA

    Studio_AKIBA

    Joined:
    Mar 3, 2014
    Posts:
    1,427
    I want to split a string (more of a paragraph, really) that I need to be able to split into each line and place each one of those lines in an array.

    I have an editor-accessible (public) string which has been filled with around 20 lines of text which I need to split into an array called lines so I can get at each line by defining the line number.

    Code (CSharp):
    1. [Multiline(20)]
    2.     public string text;
    3.     public TypePauses typePauses;
    4.     public string[] lines;
    5.  
    6.     void start()
    7.     {
    8.         lines = text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
    9.     }
    I started with the above code, believing this would work, but it doesn't appear to actually do anything.
    Am I doing something wrong, or is there a better way to do this?
     
  2. tomicz

    tomicz

    Joined:
    Mar 16, 2015
    Posts:
    152
    public TextAsset TextFile;
    void readTextFileLines() {
    string[] linesInFile = TextFile.text.Split('\n');
    foreach (string line in linesInFile)
    {
    Debug.Log(line);
    }
    }

    ---------------
    Also how do I add quote to my code ?
     
    c8theino, devon_d and kryztyan412 like this.
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,195
    How are your lines split currently in your text? Are they actually using the escape version with \n or is it you just hit enter at the end of each line and put it in a text file? (or somewhere else).
     
  4. tomicz

    tomicz

    Joined:
    Mar 16, 2015
    Posts:
    152
    Yes, as you described.
     
    kryztyan412 likes this.
  5. samf1111

    samf1111

    Joined:
    Sep 18, 2019
    Posts:
    16
    add quotes with ` character
     
    thadstedman likes this.
  6. stoupas

    stoupas

    Joined:
    Aug 26, 2021
    Posts:
    18
    If you want to get one random line (even tho you dindn't ask) you can use the code below.
    Code (CSharp):
    1. private void GetRandomLine(string file) {
    2.         var lines = file.Split('\n');
    3.  
    4.         var randomIndex = Random.Range(0, lines.Length);
    5.  
    6.         string Line = lines[randomIndex].ToString();
    7.      
    8.         print(Line);
    9. }