簡體   English   中英

解析字符串 C#

[英]Parsing string C#

所以這是我的問題,我試圖將文本文件的內容作為字符串獲取,然后對其進行解析。 我想要的是一個包含每個LireFichier且僅包含單詞的選項卡(沒有空格,沒有退格鍵,沒有 \n...)很好,因為它顯示正確)但是當我嘗試解析它失敗並開始對我的字符串進行隨機連接時,我不明白為什么。 這是我正在使用的文本文件的內容:

truc,
ohoh,
toto, tata, titi, tutu,
tete,

這是我的最終字符串:

;tete;;titi;;tata;;titi;;tutu;

應該是:

truc;ohoh;toto;tata;titi;tutu;tete;

這是我寫的代碼(所有使用都可以):

namespace ConsoleApplication1{

class Program
{
    static void Main(string[] args)
    {
        string chemin = "MYPATH";
        string res = LireFichier(chemin);
        Console.WriteLine("End of reading...");
        Console.WriteLine("{0}",res);// The result at this point is good
        Console.WriteLine("...starting parsing");
        res = parseString(res);
        Console.WriteLine("Chaine finale : {0}", res);//The result here is awfull
        Console.ReadLine();//pause
    }

    public static string LireFichier(string FilePath) //Read the file, send back a string with the text
    {
        StreamReader streamReader = new StreamReader(FilePath);
        string text = streamReader.ReadToEnd();
        streamReader.Close();
        return text;
    }

    public static string parseString(string phrase)//is suppsoed to parse the string
    {
        string fin="\n";
        char[] delimiterChars = { ' ','\n',',','\0'};
        string[] words = phrase.Split(delimiterChars);

        TabToString(words);//I check the content of my tab

        for(int i=0;i<words.Length;i++)
        {
            if (words[i] != null)
            {
                fin += words[i] +";";
                Console.WriteLine(fin);//help for debug
            }
        }
        return fin;
    }

    public static void TabToString(string[] montab)//display the content of my tab
    {
        foreach(string s in montab)
        {
            Console.WriteLine(s);
        }
    }
}//Fin de la class Program
}

我認為你的主要問題是

  string[] words = phrase.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);

您可以嘗試使用字符串拆分選項為您刪除空條目:

string[] words = phrase.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);

請參閱此處的文檔。

試試這個:

class Program
    {
        static void Main(string[] args)
        {
            var inString = LireFichier(@"C:\temp\file.txt");
            Console.WriteLine(ParseString(inString));
            Console.ReadKey();
        }

        public static string LireFichier(string FilePath) //Read the file, send back a string with the text
        {
            using (StreamReader streamReader = new StreamReader(FilePath))
            {
                string text = streamReader.ReadToEnd();
                streamReader.Close();
                return text;
            }
        }

        public static string ParseString(string input)
        {
            input = input.Replace(Environment.NewLine,string.Empty);
            input = input.Replace(" ", string.Empty);
            string[] chunks = input.Split(',');
            StringBuilder sb = new StringBuilder();
            foreach (string s in chunks)
            {
                sb.Append(s);
                sb.Append(";");
            }
            return sb.ToString(0, sb.ToString().Length - 1);
        }
    }

或這個:

public static string ParseFile(string FilePath)
{
    using (var streamReader = new StreamReader(FilePath))
    {
        return streamReader.ReadToEnd().Replace(Environment.NewLine, string.Empty).Replace(" ", string.Empty).Replace(',', ';');
    }
}

您的主要問題是您在\n上拆分,但從您的文件中讀取的換行符是\r\n

您的 output 字符串確實包含您的所有項目,但留在其中的\r字符會導致后面的“行”覆蓋控制台上較早的“行”。

\r是“返回行首”指令;如果沒有\n “移至下一行”指令,您第 1 行中的單詞將被第 2 行、第 3 行和第 4 行中的單詞覆蓋。)

除了在\r\n上拆分外,您還需要檢查字符串是否為 null或為空,然后再將其添加到 output(或者,最好使用其他人提到的StringSplitOptions.RemoveEmptyEntries )。

string ParseString(string filename) {
    return string.Join(";", System.IO.File.ReadAllLines(filename).Where(x => x.Length > 0).Select(x => string.Join(";", x.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(y => y.Trim()))).Select(z => z.Trim())) + ";";
}

暫無
暫無

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

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