【问题标题】:C# removing last delimited field from a string splitC# 从字符串拆分中删除最后一个分隔字段
【发布时间】:2023-07-18 11:51:02
【问题描述】:

我是一名初学者 c# 程序员,对我正在构建的应用程序有一个简短的问题。我的过程读取多个文件,目的是根据文本文件中的 1 或 0 管道分隔字段去除特定记录。它实际上是文件中的最后一个分隔字段。如果它是 0,我将它写入一个临时文件(稍后将替换我读取的原始文件),如果它是其他任何东西我不这样做。不要试图让它太混乱,但文件中有两种类型的记录,一个标题行,然后是一些支持行。标题行是唯一具有标志的行,因此您可以从下面看出,如果 bool 通过为 0 设置为良好记录,它会将标题记录连同其下方的所有 supp 记录一起写入,直到遇到错误在这种情况下,它将否定写入它们,直到下一个好的。

但是,我现在要做的(并且想知道最简单的方法)是如何在没有最后一个管道分隔字段(即标志)的情况下编写标题记录。由于它应该始终是该行的最后 2 个字符(例如“0|”或“1|”因为需要前面的管道),它应该是我的 inputrecord 字符串上的字符串修剪吗?有没有更简单的方法?有没有办法对记录进行拆分,但实际上不包括最后一个字段(在本例中为字段 36)?任何意见,将不胜感激。谢谢,

static void Main(string[] args)
{
    try
    {
        string executionDirectory = RemoveFlaggedRecords.Properties.Settings.Default.executionDirectory;
        string workDirectory = RemoveFlaggedRecords.Properties.Settings.Default.workingDirectory;

        string[] files = Directory.GetFiles(executionDirectory, "FilePrefix*");             
        foreach (string file in files)
        {
            string tempFile = Path.Combine(workDirectory,Path.GetFileName(file));
            using (StreamReader sr = new StreamReader(file,Encoding.Default))
            {
                StreamWriter sw = new StreamWriter(tempFile);
                string inputRecord = sr.ReadLine();

                bool goodRecord = false;
                bool isheaderRecord = false;
                while (inputRecord != null)
                {
                    string[] fields = inputRecord.Split('|');
                    if (fields[0].ToString().ToUpper() == "HEADER")
                    {                               
                        goodRecord = Convert.ToInt32(fields[36]) == 0;
                        isheaderRecord = true;
                    }

                    if (goodRecord == true && isheaderRecord == true)
                    {       
                        //    I'm not sure what to do here to write the string without the 36th field***
                    }
                    else if (goodRecord == true)
                    {
                        sw.WriteLine(inputRecord);
                    }

                    inputRecord = sr.ReadLine();
                }

                sr.Close();
                sw.Close();
                sw = null;
            }    
        }

        string[] newFiles = Directory.GetFiles(workDirectory, "fileprefix*");
        foreach (string file in newFiles)
        {
            string tempFile = Path.Combine(workDirectory, Path.GetFileName(file));
            string destFile = Path.Combine(executionDirectory, Path.GetFileName(file));

            File.Copy(tempFile, destFile, true);
            if (File.Exists(destFile))
            {
                File.Delete(tempFile);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }

    finally
    {
        // not done   
    }
}

【问题讨论】:

  • 您可以拆分,使用链接的Take(count) 获取除最后一个字段之外的所有字段,然后再次加入以写出...

标签: c# string streamreader streamwriter


【解决方案1】:

goodRecord = fields.Last().Trim() == "0";

if (inputRecord.Contains("|") string outputRecord = inputRecord.Substring(1, inputRecord.LastIndexOf("|"));

【讨论】:

    【解决方案2】:

    您可以做到这一点的一种方法-如果您在代码中想要始终在string[]中写入除最后一个元素之外的所有元素-构造一个for循环,该循环在最后一项之前终止:

    for (int i = 0; i < fields.Length - 1; i++)
    {
         // write your field here
    }
    

    这是假设您要单独编写每个字段,并且首先要遍历 fields。如果您只想在不使用循环的情况下将单个字符串写入单行,您可以这样做:

    var truncatedFields = fields.Take(fields.Length - 1);
    

    然后只要写上你认为合适的truncatedFieldsstring[]。您可以在一行中完成所有这些的一种方法可能如下所示:

    sw.WriteLine(String.Join("|", fields.Take(fields.Length - 1)));
    

    【讨论】:

    • string.Join 将分隔符作为第一个参数,将字符串集合作为第二个参数。
    • 分隔符也应该是字符串。
    • @user3494110 如果它解决了您的问题,请不要忘记投票并选择答案。
    最近更新 更多