替换字符串中间的值

替换字符串中间的值

本文介绍了替换字符串中间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我正在加载一个 .txt 文件并创建一个列表来存储它.
  • while 循环将所有文本存储到列表中.
  • 我又创建了 3 个列表来存储不同的值.
  • 我使用 REGEX 来匹配看起来像111.111"的数字.
  • 如果在行中匹配,则将其分组为X"和Y".
  • 将每个分组的项目添加到上面创建的新列表中(其中 3 个).
  • 使用 TextBox 输入值对X"和Y"值进行加法运算.
  • StringBuilder 值输出到 RichTextBoxes.

  • I am loading a .txt file and creating a list to store it in.
  • The while loop stores all of the text into the list.
  • I create 3 more lists to store different values.
  • I use REGEX to match for numbers looking like "111.111".
  • If it is a match in the line, group it as "X" and "Y".
  • Add each of the grouped items to the new lists created above (the 3 of them).
  • Use addition on the "X" and "Y" values using a TextBox input value.
  • Output the StringBuilder values to 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::: 我想要做的是获取 calculatedXRichTextBoxcalculatedYRichTextBox 和 替换 旧值 (在 fileList 中) 并输出它们以覆盖 calculatedXRichTextBoxcalculatedYRichTextBox.

NOW::: What I am trying to do is take these new values that are in the calculatedXRichTextBox and calculatedYRichTextBox and Replace the old values (in the fileList) and output them to override the calculatedXRichTextBox and 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 个不同的列表中)

(stripped values "X" and "Y" -- in 2 different lists)

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

问题:

  • 我该怎么做?

推荐答案

解决问题的另一种方法是将代码视为对数据流应用转换.

Another way to approach your problem is to think of your code as applying a transformation to a stream of data.

这基本上就是下面的示例所做的.它是为 .NET 4.0 编写的,如果您的目标是较早的运行时,则必须使用 ReadAllLines 方法(相对于 ReadLines),而不是使用 Tuple 你需要创建一个容器类(它可以是私有的这个类)从您的函数返回多个值.

That's basically what the sample below does. It was written for .NET 4.0, if you are targeting an earlier runtime you'll have to use the ReadAllLines method (as opposed to ReadLines) and instead of using a Tuple you'll need to make a container class (which can be private to this class) to return multiple values from your function.

void calculateXAndYPlacement()
{
    // Read data from file
    var path = @"[path to your document]";
    var data = File.ReadLines(path + "data.txt");

    // Parse the values you'll be modifying your data by
    var doubleXValue = double.Parse(xDisplacementTextBox.Text);
    var doubleYValue = double.Parse(yDisplacementTextBox.Text);

    // apply your transformation to all valid lines of data
    var modifiedData = from line in data
                       where LineIsValid( line )
                       select ModifyLine( line, doubleXValue, doubleYValue );

    // Do what you wish with the data
    foreach( var dataPoint in modifiedData )
    {
         // grab the values from the Tuple and put them into the
         // appropriate text boxes.
    }
}

Tuple<string,double,double> ModifyLine(string data, double xValue, double yValue)
{
    // split line into parts
    var columns = Regex.Split(data, @"\s+");
    columns.Dump();
    // do your math on each part, I just assigned the new values
    // for the sake of the example.
    columns[3] = xValue.ToString();
    columns[4] = yValue.ToString();

    // recombine the line
    return Tuple.Create( string.Join(" ", columns), xValue, yValue );
}

bool LineIsValid(string lineData)
{
    return Regex.IsMatch(lineData, @"(?<x>-?\d+\.\d+)\s+(?<y>-?\d+\.\d+)");
}

这篇关于替换字符串中间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 05:41