[英]Edit a string of 685 characters and replace substring with another string in C#
Browse for a folder containing specific files using a folder dialog... 使用文件夹对话框浏览包含特定文件的文件夹...
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());
}
}
Update the file ... 更新文件...
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());
}
}
I need to replace the 655th position of a string which is of 29 Characters(combination of first & last name of a person seperated by a whitespace), but the problem is the how to maintain fix length of a string which is of 685 characters long? 我需要替换29个字符的字符串的第655位(用空格分隔的人的姓氏和名字的组合),但是问题是如何保持685个字符长的字符串的固定长度?
I think that you should make newString
exactlly 29 characters long: 我认为你应该做
newString
exactlly长29个字符:
if (newString.Length > 29) newString = newString.Substring(0, 29);
if (newString.Length < 29) newString = newString.PadRight(29);
This code trims string if it is longer than 29 charaters or pads right side with spaces if string is shorter than 29 characters. 如果字符串长于29个字符,则此代码会修剪字符串;如果字符串短于29个字符,则此代码会在空格的右侧填充空格。
You can use StringBuilder class. 您可以使用StringBuilder类。
Ex: replace defg
with 1234
例如:用
1234
代替defg
StringBuilder sb = new StringBuilder( "abcdefghi");
var newstr = sb.Remove(3, 4).Insert(3, "1234").ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.