c# - 解析字符串 C#

标签 c# parsing file-io

所以这是我的问题,我试图将文本文件的内容作为字符串获取,然后对其进行解析。我想要的是一个包含每个单词且仅包含单词的选项卡(没有空格,没有退格键,没有\n ...)我正在做的是使用函数 LireFichier 将包含文件中的文本(工作正常,因为它显示正确)但是当我尝试解析它失败并开始对我的字符串进行随机连接时,我不明白为什么。 这是我正在使用的文本文件的内容:

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

关于c# - 解析字符串 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10102419/

相关文章:

c# - 基于ASP.NET的MMOG的可行性

C# 泛型语法帮助

android - 如何用Java代码解析上传的apk文件?

用 JavaScript 编写的 Java 解析器

java - 使用Java发送POST数据

visual-studio-code - VSCode 扩展写入和打开文件

c# - 链接按钮点击事件

c# - MVVM 设置 MenuItem 的 DataContext

c++ - C++读取二进制文件的方法

c - 在c中读取二进制文件的各个部分