C# 更新文本文件C中的特定行#
我正在尝试使用以下条件更新文本文件中的特定行: 如果行包含要搜索的单词,则只删除下一个空格 使用以下代码:C# 更新文本文件C中的特定行#,c#,asp.net,.net,C#,Asp.net,.net,我正在尝试使用以下条件更新文本文件中的特定行: 如果行包含要搜索的单词,则只删除下一个空格 使用以下代码: using (System.IO.TextReader tr = File.OpenText((@"d:\\My File3.log"))) { string line; while ((line = tr.ReadLine()) != null) {
using (System.IO.TextReader tr = File.OpenText((@"d:\\My File3.log")))
{
string line;
while ((line = tr.ReadLine()) != null)
{
string[] items = line.Trim().Split(' ');
foreach (var s in items)
{
if (s == "a" || s == "b")
s = s.Replace(" ", "");
using (StreamWriter tw = new StreamWriter(@"d:\\My File3.log"))
tw.WriteLine(s);
我的文件类似于:
k l m
x y z a c
b d a w
更新文件应类似于:
k l m
x y zac
bdaw我想你可以通过以下方式来实现:
...
if (s == "a" || s == "b"){
if (s == "a")
s = s.Replace("a ", "a");
if (s == "b")
s = s.Replace("b ", "b");
using (StreamWriter tw = new StreamWriter(@"d:\\My File3.log"))
tw.WriteLine(s);
}
...
样本:
string test="a c";
test =test.Replace("a ", "a");
Console.WriteLine(test);
输出:
ac你在找什么
一般情况下,例如
如果行包含要搜索的单词
意味着a
和b
应该是单词(b
在abc
中不是我们要找的单词):
尝试使用正则表达式:
试试这个:
....
while ((line = tr.ReadLine()) != null)
{
using (StreamWriter tw = new StreamWriter(@"d:\\My File3.log"))
string st = line.Replace("a ", "a").Replace("b ", "b");//just add additional .Replace() here
tw.WriteLine(st);
}
我认为,你的问题在于:
if (s == "a" || s == "b")
s = s.Replace(" ", "");
为了满足if
条件,字符串
s
中必须没有空格。因此,您的代码不起任何作用
if(s == "a" || s == "b")
foreach(var s2 in items)
{
if(items.IndexOf(s2) > items.IndexOf(s) && s2 == " ")
s2 == string.Empty;
break;
}
break
的存在是为了确保我们只替换下一个空格,而不是字符后面的所有空格> P>在FACH循环之前应考虑一个临时变量
int temp = 0;
foreach(var s in items)
{
if (temp == 0)
{
if (s == "a" || s == "b")
{
temp = 1;
}
}
else
{
s = s.Replace(" ", "");
using (StreamWriter tw = new StreamWriter(@"d:\\My File3.log"))
tw.WriteLine(s);
temp = 0;
}
}
不能在同一次迭代中读取和写入同一文件。 下面是一个使用StringBuilder的解决方案(通过他,您可以操作字符串中的字符):
if (s == "a" || s == "b")
s = s.Replace(" ", "");
if(s == "a" || s == "b")
foreach(var s2 in items)
{
if(items.IndexOf(s2) > items.IndexOf(s) && s2 == " ")
s2 == string.Empty;
break;
}
int temp = 0;
foreach(var s in items)
{
if (temp == 0)
{
if (s == "a" || s == "b")
{
temp = 1;
}
}
else
{
s = s.Replace(" ", "");
using (StreamWriter tw = new StreamWriter(@"d:\\My File3.log"))
tw.WriteLine(s);
temp = 0;
}
}
using (StreamWriter tw = new StreamWriter(@"file1.txt"))
{
using (System.IO.TextReader tr = File.OpenText((@"file.txt")))
{
string line;
StringBuilder items = new StringBuilder();
while ((line = tr.ReadLine()) != null)
{
items.Append(line);
items.Replace("a ", "a");
items.Replace("b ", "b");
tw.WriteLine(items);
items.Clear();
}
}
}