异常“字符串长度不能为零”
我们试图从文本文件中读取每个单词并用另一个单词替换它。 对于较小的文本文件,它效果很好。但对于较大的文本文件,我们不断收到异常:“字符串长度不能为零。 参数名称:oldValue "
void replace()
{
string s1 = " ", s2 = " ";
StreamReader streamReader;
streamReader = File.OpenText("C:\\sample.txt");
StreamWriter streamWriter = File.CreateText("C:\\sample1.txt");
//int x = st.Rows.Count;
while ((line = streamReader.ReadLine()) != null)
{
char[] delimiterChars = { ' ', '\t' };
String[] words = line.Split(delimiterChars);
foreach (string str in words)
{
s1 = str;
DataRow drow = st.Rows.Find(str);
if (drow != null)
{
index = st.Rows.IndexOf(drow);
s2 = Convert.ToString(st.Rows[index]["Binary"]);
s2 += "000";
// Console.WriteLine(s1);
// Console.WriteLine(s2);
streamWriter.Write(s1.Replace(s1,s2)); // Exception occurs here
}
else
break;
}
}
streamReader.Close();
streamWriter.Close();
}
我们无法找到原因。 提前致谢。
We are trying to read each word from a text file and replace it with another word.
For smaller text files, it works well. But for larger text files we keep getting the exception: "String cannot be of zero length.
Parameter name: oldValue "
void replace()
{
string s1 = " ", s2 = " ";
StreamReader streamReader;
streamReader = File.OpenText("C:\\sample.txt");
StreamWriter streamWriter = File.CreateText("C:\\sample1.txt");
//int x = st.Rows.Count;
while ((line = streamReader.ReadLine()) != null)
{
char[] delimiterChars = { ' ', '\t' };
String[] words = line.Split(delimiterChars);
foreach (string str in words)
{
s1 = str;
DataRow drow = st.Rows.Find(str);
if (drow != null)
{
index = st.Rows.IndexOf(drow);
s2 = Convert.ToString(st.Rows[index]["Binary"]);
s2 += "000";
// Console.WriteLine(s1);
// Console.WriteLine(s2);
streamWriter.Write(s1.Replace(s1,s2)); // Exception occurs here
}
else
break;
}
}
streamReader.Close();
streamWriter.Close();
}
we're unable to find the reason.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您执行
string.Split
时,您可能会如果序列中有多个空格或制表符,则获取空条目。这些无法替换,因为字符串长度为 0。使用
StringSplitOptions
参数的重载来去除空结果:When you do your
string.Split
you may get empty entries if there are multiple spaces or tabs in sequence. These can't be replaced as the strings are 0 length.Use the overload that strips empty results using the
StringSplitOptions
argument:发生异常是因为
s1
在某些时候是空字符串。您可以通过将此行替换为以下内容来避免这种情况:
The exception occurs because
s1
is an empty string at some point. You can avoid this by replacing the linewith this:
您想像这样更改 Split 方法调用:
You want to change your Split method call like this:
这意味着 s1 包含一个空字符串 (""),如果文件中有两个连续的空格或制表符,就会发生这种情况。
It means that s1 contains an empty string ("") which can happen if you have two consecutive white spaces or tabs in your file.