日期:2014-05-19  浏览次数:21200 次

c#如何处理这样的STRING
string   abc= "fdjlsakjfdslk   @a   23423prujfsdjlf@b   23erjdwos@c   435r43 "
替换@a   @b   @c   为X   Y   Z

要求
1参数个数并不规定
2参数名称不确定
3   只有@确定

------解决方案--------------------
//参考如下代码
private string ReplaceParam(string AStr, Dictionary <string, string> AParams)
{
if (AStr == string.Empty || AStr == null || AParams == null) return AStr;
string Result = AStr;

foreach (string vKey in AParams.Keys)
Result = Result.Replace( "@ " + vKey, AParams[vKey]);
return Result;
}

private void Form1_Load(object sender, EventArgs e)
{
Dictionary <string, string> vParams = new Dictionary <string, string> ();
vParams.Add( "a ", "X ");
vParams.Add( "b ", "Y ");
vParams.Add( "c ", "Z ");

string abc = "fdjlsakjfdslk @a 23423prujfsdjlf@b 23erjdwos@c 435r43 ";
Text = ReplaceParam(abc, vParams);
}

------解决方案--------------------
private string ReplaceSpecified(string line, string[] oldStrings, string[] newStrings)
{
if (oldStrings.Length == newStrings.Length)
{
for (int i = 0; i < oldStrings.Length; i++)
{
string pattern = @oldStrings[i];
line = Regex.Replace(line, pattern, newStrings[i]);
}
}

return line;
}


string abc = "fdjlsakjfdslk @a 23423prujfsdjlf@b 23erjdwos@c 435r43 ";
abc = ReplaceSpecified(abc, new string[] { "@a ", "@b ", "@c " }, new string[] { "X ", "Y ", "Z " });
------解决方案--------------------
你早给结果就是了,这样

using System.Text.RegularExpressions;

string abc1 = "fdjlsakjfdslk (@a) 23423prujfsdjlf(@b) 23erjdwos(@w) 435r43 ";
string result = Regex.Replace(abc1, @ "@(\w) ", new MatchEvaluator(expreplace));


private string expreplace(Match m)
{
return m.Groups[1].Value.ToUpper();
}

输出:fdjlsakjfdslk (A) 23423prujfsdjlf(B) 23erjdwos(W) 435r43