簡體   English   中英

C# 從 .txt 文件中讀取字符串

[英]C# Reading a string from a .txt file

my.txt 文件的片段如下所示:

18  Ladders/ladder_trigger (18 triggers) (18 enabled)
17  assets/prefabs/player/player_model.prefab/collision (0 triggers) (1 enabled)
17  assets/prefabs/misc/xmas/poweredlights/xmas.advanced.lights.deployed.prefab
(0 triggers) (17 enabled)

有 +1000 行,它們的順序總是隨機的。 我的問題是我正在嘗試獲取一個 int,其中包含一行中啟用的值的數量,該行始終包含文本assets/prefabs/player/player_model.prefab/collision和 output 它在控制台中。 總是只有 1 行包含assets/prefabs/player/player_model.prefab/collision啟用值的數量可能不同,文本文件中的 position 總是不同的。 我試圖檢查這個特定字符串的整個文本文件,然后嘗試從那里弄清楚如何獲取該數字,但我不知道如何做到這一點。 這是我的代碼的一部分,它工作正常,但僅用於檢查文件是否包含該字符串,而不是用於獲取之后的數字。

            string[] words = File.ReadAllText(@"C:\Users\azir\Desktop\KelosRPR\Physics.Colliders.Objects.txt").Split(' ');
            string wordtobesearched = "assets/prefabs/player/player_model.prefab/collision";
            bool condition = false;
            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Contains(wordtobesearched) == true)
                {
                    condition = true;
                    break;
                }
                else
                {
                    condition = false;
                }
            }
            if (condition == true)
            {
                Console.WriteLine("{0} found in data", wordtobesearched);
            }
            else
            {
                Console.WriteLine("{0} not found in data", wordtobesearched);
            }

您可以使用正則表達式來查找enabled的號碼。 這是一個例子。

var text = File.ReadAllText(@"C:\Users\azir\Desktop\KelosRPR\Physics.Colliders.Objects.txt");
var wordtobesearched = "assets/prefabs/player/player_model.prefab/collision";
var regex = new Regex($"{wordtobesearched}.*?\\((\\d+) enabled\\)");
var number = int.Parse(regex.Match(text).Groups[1].Value);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM