【发布时间】:2011-10-14 10:20:57
【问题描述】:
以下代码说明:
- 我正在加载一个 .txt 文件并创建一个列表来存储它。
-
while循环将所有文本存储到列表中。 - 我再创建 3 个列表来存储不同的值。
- 我使用 REGEX 来匹配看起来像“111.111”的数字。
- 如果是匹配的行,将其分组为“X”和“Y”。
- 将每个分组的项目添加到上面创建的新列表(其中 3 个)中。
- 使用
TextBox输入值对“X”和“Y”值进行加法运算。 -
将
StringBuilder的值输出到RichTextBoxes。private void calculateXAndYPlacement() {s // Reads the lines in the file to format. var fileReader = File.OpenText(filePath + "\\Calculating X,Y File.txt"); // Creates a list for the lines to be stored in. var fileList = new List<string>(); // Adds each line in the file to the list. var fileLines = ""; #UPDATED @Corey Ogburn while ((fileLines = fileReader.ReadLine()) != null) #UPDATED @Corey Ogburn fileList.Add(fileLines); #UPDATED @Corey Ogburn // Creates new lists to hold certain matches for each list. var xyResult = new List<string>(); var xResult = new List<string>(); var yResult = new List<string>(); // Iterate over each line in the file and extract the x and y values fileList.ForEach(line => { Match xyMatch = Regex.Match(line, @"(?<x>-?\d+\.\d+)\s+(?<y>-?\d+\.\d+)"); if (xyMatch.Success) { // Grab the x and y values from the regular expression match String xValue = xyMatch.Groups["x"].Value; String yValue = xyMatch.Groups["y"].Value; // Add these two values, separated by a space, to the "xyResult" list. xyResult.Add(String.Join(" ", new[]{ xValue, yValue })); // Add the results to the lists. xResult.Add(xValue); yResult.Add(yValue); // Calculate the X & Y values (including the x & y displacements) double doubleX = double.Parse(xValue); double doubleXValue = double.Parse(xDisplacementTextBox.Text); StringBuilder sbX = new StringBuilder(); sbX.AppendLine((doubleX + doubleXValue).ToString()); double doubleY = double.Parse(yValue); double doubleYValue = double.Parse(yDisplacementTextBox.Text); StringBuilder sbY = new StringBuilder(); sbY.AppendLine((doubleY + doubleYValue).ToString()); calculatedXRichTextBox.AppendText(sbX + "\n"); calculatedYRichTextBox.AppendText(sbY + "\n"); } }); }
NOW::: 我要做的是采用 calculatedXRichTextBox 和 calculatedYRichTextBox 中的这些新值并 替换 strong> 旧值(在文件列表中) 并输出它们以覆盖calculatedXRichTextBox 和calculatedYRichTextBox。
所以,我的价值观是:
(原始文件)
TEXT TEXT 227.905 203.244 180
TEXT TEXT 242.210 181.294 180
TEXT TEXT 236.135 198.644 90
(剥离值“X”和“Y”——在 2 个不同的列表中)
227.905 203.244
242.210 181.294
236.135 198.644
(计算值将“10”添加到“X”和“20”添加到“Y”——将它们放入 2 个不同的RichTextBoxes)
237.905 223.244
252.210 201.294
246.135 218.644
(这是我想要结束的结果——原始文件 + 计算值替换旧值)
TEXT TEXT 237.905 223.244 180
TEXT TEXT 252.210 201.294 180
TEXT TEXT 246.135 218.644 90
问题:
- 我该怎么做?
【问题讨论】:
-
小点:File.ReadAllLines() 会避免早期的代码,调用 List.ForEach 而不是直接使用 foreach 循环是没有意义的。
-
我建议不要在您的上下文中使用 while(true)。您可以轻松地将检查移动到 while 语句的条件中:while ((line = fileReader.ReadLine()) != null) {...}.
-
@Jon Skeet:感谢您的小分:)
-
@Corey Ogburn:你为什么反对它?
-
while(true) 意味着您将永远奔跑。相反,您只是在有另一行要读取时循环。您的代码说“我将永远运行......或直到发生这种情况”,而不是说“我将运行直到发生这种情况”。不过,我会推荐@Jon Skeet 的回答而不是我的,如果你不需要的话,不需要循环。
标签: c# regex string replace richtextbox