【问题标题】:How to read specific line from String? Unity C#如何从字符串中读取特定行?统一 C#
【发布时间】:2018-05-03 13:57:38
【问题描述】:

我可以从 Unity 中的字符串文件中读取特定的行吗?更具体地说,我可以将字符串中的特定行分配给另一个字符串吗?

基本上我想要实现的是从互联网下载文本文件,测量其中有多少行,然后将随机行分配给另一个字符串。 到目前为止,我已经设法下载了字符串并测量了有多少行,但我无法弄清楚如何读取特定的字符串行。

当前代码(下载文本文件,分配给字符串变量并测量行数):

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

【问题讨论】:

    标签: c# android string unity3d


    【解决方案1】:

    你快到了。

    // 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];
    

    另外,您提到想要“分配一条随机线”。我不知道你是不是字面上的意思,但如果是这样,让我们​​更进一步:

    // 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];
    

    【讨论】:

      猜你喜欢
      • 2016-03-22
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多