【问题标题】:Edit a string of 685 characters and replace substring with another string in C#在 C# 中编辑一个 685 个字符的字符串并将子字符串替换为另一个字符串
【发布时间】:2023-03-22 09:58:01
【问题描述】:

使用文件夹对话框浏览包含特定文件的文件夹...

private void btnBrowse_Click(object sender, EventArgs e)
    {
        DialogResult result = fbdPath.ShowDialog();
        if (result == DialogResult.OK)
        {
            string[] files = Directory.GetFiles(fbdPath.SelectedPath);
            txtPath.Text = fbdPath.SelectedPath;
            MessageBox.Show(txtPath.Text.ToString());
        }
    }

更新文件...

try
        {
            String path = txtPath.Text;
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] files = dir.GetFiles();
            foreach( FileInfo file in files)
            {
                StreamReader sReader;
                sReader = File.OpenText(dir + @"\" + file.Name );

                StreamWriter sWriter = new StreamWriter(@"f:\" + file.Name);
                while (sReader.EndOfStream == false)
                {
                    string contents = sReader.ReadLine();

                    String Flag = contents.Substring(655, 29);

                    String emBossFName = contents.Substring(41, 40);
                    String emBossLName = contents.Substring(121, 40);

                    String emBossFullName = emBossFName.Trim() + " " + emBossLName.Trim();

                    String newString = emBossFullName;

                    sWriter.WriteLine(contents.Replace(Flag, newString));
                }
                sWriter.Close();
                sReader.Close();
            }
        }
        catch (IOException ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
    }

我需要替换 29 个字符的字符串的第 655 位(由空格分隔的人的名字和姓氏的组合),但问题是如何保持字符串的固定长度685 个字符长?

【问题讨论】:

    标签: c# replace substring


    【解决方案1】:

    只需获取最后一个字符串并致电Remove

    "...".Remove(684);
    

    而且,如果你担心它不够长,你可以先使用PadRight

    【讨论】:

      【解决方案2】:

      我认为你应该使 newString 正好 29 个字符长:

      if (newString.Length > 29) newString = newString.Substring(0, 29);
      if (newString.Length < 29) newString = newString.PadRight(29);
      

      如果字符串长于 29 个字符,此代码将修剪字符串,如果字符串短于 29 个字符,则用空格填充右侧。

      【讨论】:

        【解决方案3】:

        您可以使用 StringBuilder 类。

        例如:将defg 替换为1234

        StringBuilder sb = new StringBuilder( "abcdefghi");
        var newstr = sb.Remove(3, 4).Insert(3, "1234").ToString();
        

        【讨论】:

          猜你喜欢
          • 2011-06-06
          • 1970-01-01
          • 2011-04-06
          • 2012-07-16
          • 1970-01-01
          • 2021-06-15
          • 1970-01-01
          • 2013-12-03
          • 1970-01-01
          相关资源
          最近更新 更多