如何用条件替换特定行中的特定单词 [英] How to replace specific word in specific line with condition
本文介绍了如何用条件替换特定行中的特定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的文本文件:
I have a text file like this :
CHECK_CONFIG = 0$
LANGUAGE = en$
SERVER = localhost$
SERVERM = localhost$
我需要更换任何值的 SERVER = localhost $
中的localhost...
我尝试了什么:
我试着写这个代码
I need to replace "localhost" in SERVER = localhost$
with any value...
What I have tried:
I tried to write this code
public static string readConfTextStartWith(string path, string startsWith)
{
string Value = "";
foreach (var line in File.ReadLines(path))
{
if (line.StartsWith(startsWith))
{
string str = line.Split('=')[1].Trim();
Value = Convert.ToString(str.Substring(0, str.Length - (str.Length - str.LastIndexOf('$'))));
}
}
return Value;
}
public static void replaceText(string path, string startsWith, string replacement)
{
string word = readConfTextStartWith(path, startsWith);
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith(startsWith))
{
line = line.Replace(word, replacement);
// here what i can't to do
// i went to write one line but this code clear all text and add this line only
File.WriteAllText(path, line);
}
}
reader.Close();
}
}
Functions.replaceText("configA.txt", "SERVER","localhost");
推荐答案
LANGUAGE = zh
LANGUAGE = en
SERVER = localhost
SERVER = localhost
SERVERM = localhost
SERVERM = localhost
这篇关于如何用条件替换特定行中的特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文