有一个文件a.txt,里面有很多如果Order_head,A_dddd,等字符
1、下划线 都去掉
如 Order_head 变为 OrderHead
2、注意去掉 的 下划线后的字母都要大写:
如: Order_head_id 变为 OrderHeadId
'H' 和 'I' 要大写。
请问如何写????
1、下划线 都去掉
如 Order_head 变为 OrderHead
2、注意去掉 的 下划线后的字母都要大写:
如: Order_head_id 变为 OrderHeadId
'H' 和 'I' 要大写。
请问如何写????
用StreamRead读出来,拆开放到字符串里做Replace(),ToLower()等操作,
然后再用StreamWriter,写回去。
Regex.Replace方法。
{
string sTextFilePath = @"E:\CSharp.Coding\TextReplacer\TextReplacer\a1.txt";
string sFind="";
for (int i = 48; i <= 57; i++)
{
char c = (char)i;
sFind = c.ToString();
DoReplace(sTextFilePath, sFind, "_" + sFind, true);
//MessageBox.Show(sFind);
}
for (int i = 97; i <= 122; i++)
{
char c = (char)i;
sFind = c.ToString();
DoReplace(sTextFilePath, sFind, "_" + sFind, true);
//MessageBox.Show(sFind);
}
MessageBox.Show("Replace is compled!");
}
private static void DoReplace(string fileFullName, string replacedBy, string findPattern, bool isBackup)
{
string result = string.Empty;
string inputText = string.Empty;
string replacement = replacedBy;
string pat = findPattern;
Regex r = new Regex(pat, RegexOptions.Compiled);
try
{
using (StreamReader sr = new StreamReader(fileFullName))
{
inputText = sr.ReadToEnd();
}
if (r.IsMatch(inputText))
{
if (isBackup == true)
{
try
{
File.Copy(fileFullName, fileFullName + ".bak");
}
catch(System.IO.IOException ex)
{
File.Copy(fileFullName, fileFullName + ".bak", true);
MessageBox.Show(ex.Message.ToString());
}
}
result = r.Replace(inputText, replacement);
using (StreamWriter sw = new StreamWriter(fileFullName))
{
sw.Write(result);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}