C# String 的分割读取

[
Name:Rem
Age:12
]

txt文件内容如上,注意要保存成utf-8格式

下面看如何用代码将Name和Age解析出来。(这里的格式就是Key value格式。)

public class TextParse:MonoBehaviour{

private void Awake()
        {
            ReadText("GalgameText");
        }


public void ReadText(string textPath)
        {
            Dictionary<string, string> dics = new Dictionary<string, string>();
            string dt = Resources.Load<TextAsset>(textPath).text;
            string[] lines = dt.Split('\n'); //用\n表示换行符 注意是char类型 分割行
            foreach (var item in lines)
            {
                if (item.Contains(":"))
                {
                    string[] infos = item.Split(':');
                    dics.Add(infos[0], infos[1]);
                }
            }
            //遍历以下 输出到Unity控制台
            foreach (var item in dics)
            {
                Debug.Log(string.Format("{0} : {1}", item.Key, item.Value));
            }
        }


}

主要注意的就是要分割成一行行的 我们就需要根据‘\n’ (换行符) 来split

猜你喜欢

转载自blog.csdn.net/qq_14812585/article/details/86214552