替换C#中字符串的首次出现 [英] Replace first occurence of a string in c#
问题描述
以下是用于替换文件中字符串首次出现的代码.
The following is the code for replacing fist occurrence of a string in a file.
public static string ReplaceFirstOccurrance(string original, string oldValue, string newValue)
{
if (String.IsNullOrEmpty(original))
return String.Empty;
if (String.IsNullOrEmpty(oldValue))
return original;
if (String.IsNullOrEmpty(newValue))
newValue = String.Empty;
int loc = original.IndexOf(oldValue);
if(loc==-1)
return original;
return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
}
如果我要替换的字符串是文件的最后一行,那么它就不会被替换.知道为什么会发生这种情况吗?
这是我从中调用该函数的代码
If the string that I want to replace is the last line of the file then it is not getting replaced.Any idea why this is happening?
This is the code from where I am calling the function
private void Transform_Click(object sender, EventArgs e)
{
FileStream fread = new FileStream(despath, FileMode.Open);
StreamReader sfread = new StreamReader(fread);
string txt = sfread.ReadToEnd();
fread.Close();
string actual ="This is actual Sample";
string replace = "This is replaced line"+count;
string replaceVariable = ReplaceFirstOccurrance(txt, actual, replace);
FileStream filewrite = new FileStream(despath, FileMode.Create);
StreamWriter filew = new StreamWriter(filewrite);
filew.Write(replaceVariable);
filew.Close();
filewrite.Close();
count++;
}
如果这是实际示例"是文件中的最后一行,则不会替换它.
If "This is actual sample" is the last line in the file,it is not getting replaced.
推荐答案
,因为它删除了位置,所以insert()找不到任何内容loc
尝试为您的行返回"original.Remove(loc,oldValue.Length).Insert(loc,newValue);"
because it deletes the position, insert() doesnt find any loc
try this instead for your line return "original.Remove(loc, oldValue.Length).Insert(loc, newValue);"
string temp = orignal.Substring(0, orignal.IndexOf(oldv));
string temp2 = orignal.Substring(orignal.IndexOf(oldv) + oldv.Length);
return temp + newv + temp2;
使用string.Replace()
有什么问题?
And what is wrong with usingstring.Replace()
?
if (original==null) return string.Empty
else return original.Replace(oldValue, newValue);
另外,您不是逐行读取文件,而是一次将整个文件读入一个字符串中.如果您在2个或更多位置有这是实际示例",则仅第一个将被替换.
逐行读取和替换:
Also, you are not reading file line by line, you read it whole at once into one string. If you have "This is actual sample" in 2 or more places, only first will be replaced.
Reading and replaceing line by line:
private void Transform_Click(object sender, EventArgs e)
{
FileStream fread = new FileStream(despath, FileMode.Open);
StreamReader sfread = new StreamReader(fread);
FileStream filewrite = new FileStream(despath, FileMode.Create);
StreamWriter filew = new StreamWriter(filewrite);
while (!sfread.EndOfStream)
{
string line = sfread.ReadLine();
string replaceVariable = ReplaceFirstOccurrance(line,
"This is actual Sample",
"This is replaced line"+count.ToString());
filew.Write(replaceVariable);
count++;
}
filew.Close();
filewrite.Close();
fread.Close();
}
这篇关于替换C#中字符串的首次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!