[英]C# removing last delimited field from a string split
我是一名初學c#程序員,對我正在構建的應用程序有一個快速的問題。 我的進程讀入多個文件,目的是根據文本文件中的1或0管道分隔字段刪除特定記錄。 它實際上是文件中的最后一個分隔字段。 如果它是0,我將它寫入臨時文件(稍后將替換我讀取的原始文件),如果它是我沒有的其他內容。 而不是試圖讓它太混亂,但文件中有兩種類型的記錄,一個標題行,然后是幾個支持行。 標題行是唯一具有該標志的行,因此您可以從下面看出,如果bool通過為0設置為良好記錄,它會將標題記錄與其下面的所有supp記錄一起寫入,直到它遇到錯誤在這種情況下,它將否定寫入它們直到下一個好的。
但是,我現在要做的事情(並且想知道最簡單的方法)是如何在沒有最后一個管道分隔字段(IE標志)的情況下編寫頭記錄。 因為它應該總是行的最后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
}
}
一種方法可以做到這一點 - 如果你想在代碼中的那一點總是寫出除了string[]
的最后一個元素之外的所有元素 - 構造一個在最后一個項目之前終止的for
循環:
for (int i = 0; i < fields.Length - 1; i++)
{
// write your field here
}
這假設您要單獨編寫每個字段,並且您希望首先遍歷fields
。 如果您只想在不使用循環的情況下將單個字符串寫入單行,則可以執行以下操作:
var truncatedFields = fields.Take(fields.Length - 1);
然后根據需要編寫truncatedFields
string[]
。 你可以在一行中完成所有這些的一種方式可能是這樣的:
sw.WriteLine(String.Join("|", fields.Take(fields.Length - 1)));
goodRecord = fields.Last()。Trim()==“0”;
if(inputRecord.Contains(“|”)string outputRecord = inputRecord.Substring(1,inputRecord.LastIndexOf(“|”));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.