DesperateTears
DesperateTears

Reputation: 23

How to read specific line from String? Unity C#

Can I read a specific line from String file in Unity? To be more specific can I assign a specific line from String to another String?

Basically what I'm trying to achieve is to download text file from internet, measure how many lines are in it and then assign a random line to another string. So far I have managed to download the String and measure how many lines there are, but I cannot figure out how read a specific line of string.

Current code (downloads text file, get assigned to String variable and measures the amount of lines):

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine.Networking;
    using UnityEngine.UI;

    public class PickRandomLine : MonoBehaviour {
        string teksts;
        string url = "http://website.com/teksts.txt";

        public void Zajebal(){
            StartCoroutine (LudzuBled ());
        }

        IEnumerator LudzuBled(){
            yield return 0;
            WWW teksts2 = new WWW(url);
            yield return teksts2;
            teksts = teksts2.text;
            print (teksts);
            int numLines = teksts.Split('\n').Length;
            print ("linijas: " + numLines);
    }
}

Upvotes: 1

Views: 2506

Answers (1)

egnomerator
egnomerator

Reputation: 1115

You're almost there.

// this gives you all the lines in a string array
var lines = teksts.Split('\n');

// assign a specific line by index
var specificLine = lines[0];

Also, you mentioned wanting to "assign a random line." I don't know if you meant that literally, but if so lets take it a step further:

// get your random number between zero and the number of lines
var random = new Random();
var randomNumber = random.Next(0, numLines);

// assign a random line by index
var randomLine = lines[randomNumber];

Upvotes: 1

Related Questions