【问题标题】:Why doesn't a string get replaced when using the Replace method? [duplicate]为什么在使用 Replace 方法时字符串不会被替换? [复制]
【发布时间】:2014-06-28 03:53:40
【问题描述】:
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            label1.Text = "Completed";
            string tables = this.webBrowser1.Document.GetElementById("tblProducts").InnerText;
            var lines = tables.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
            string line1 = lines[0];
            string newline1 = line1.Insert(54, ", ").Insert(36, ", ").Insert(32, ", ").Insert(23, ", ").Insert(12, ", ").Insert(4, ", ");
            lines[0].Replace(line1, newline1);
            lines.Insert(1, "");
            string newText = string.Join(Environment.NewLine, lines);
            StreamWriter w = new StreamWriter(@"c:\temp\table\Table" + count.ToString("D6") + ".txt");
            w.WriteLine(newText);
            w.Close();
            complete = true;
            count ++;
        }

line1 conteint 是: 然后我在换行符 1 中插入空格:תאור,סוג פריט,מספר קטלוגי,תוצר הרכב,מצאי,תוקף וחלות הצאחריות,רחריות,רחי

但最后在 newText 中我看到了旧行。 line1 而不是 newline1。 尝试过 lines[0].Replace(line1, newline1);还有 lines[0].Replace(newline1, line1);但我仍然一直看到旧线路。

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    像任何字符串操作一样,您必须将新值分配回原来的值:

    lines[0] = lines[0].Replace(line1, newline1);
    

    但在这种情况下,由于您要替换 整个 行,您可以这样做:

    lines[0] = newline1;
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      相关资源
      最近更新 更多