解析字符串 C#

3

这里是我的问题,我正在尝试将文本文件的内容作为字符串获取,然后解析它。我想要的是一个包含每个单词的制表符,并且只有单词(没有空格、回车、\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
}

2
var newstr = String.Join(";", Regex.Matches(File.ReadAllText(@"c:\temp\aa.txt"), @"[\w\d]+").Cast<Match>().Select(m => m.Value)); - L.B
5个回答

8
我认为您的主要问题是:
  string[] words = phrase.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);

实际上,这几乎解决了问题,它克服了最终字符串中双;;的问题,但仍然有一些错误,例如txt文件中缺少某些单词。 - WizLiz
1
@WizardLizard,请查看我的或StaWho的答案,了解缺失单词的问题。 - Rawling
@Henk Holterman: 我仍然不明白为什么“truc”和“ohoh”会消失,而“tete”会放在字符串的开头。 - WizLiz
@Rawling 非常感谢,StaWho 给了我解决方案。对于每个人,感谢你们的快速回答。 - WizLiz

2
您可以尝试使用字符串分割选项来删除空条目:
string[] words = phrase.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);

请查看 此处 的文档。


1

试试这个:

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(',', ';');
    }
}

那很有用,非常感谢,我正在学习你现在所做的。 - WizLiz
@Wiz 如果这个答案对你有帮助,请点击投票按钮旁边的灰色勾号将其标记为已接受。这将给作者一些声誉。相对于其他高票但不完整的答案,它也会使他的答案更加突出,因此其他人更有可能给他一些声誉。 - Rawling

1

你的主要问题在于你正在使用\n进行分割,但从文件中读取的换行符是\r\n

你的输出字符串包含了所有的项目,但其中留下的\r字符会导致后面的“行”覆盖掉前面的“行”在控制台上显示。

(\r是一个“返回到行首”的指令;没有\n“移动到下一行”的指令,第一行的文字被第二行、第三行和第四行的文字覆盖了。)

除了在\n上进行分割之外,你还需要检查一个字符串是否为null或为空,然后再将其添加到你的输出中(或者最好使用StringSplitOptions.RemoveEmptyEntries,正如其他人所提到的那样)。


0
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())) + ";";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接