日期:2014-05-20  浏览次数:20864 次

从代码模板到代码
代码模板为
string   templete   =   " "http://www.myside.com/default.aspx?a=stra&b=strb&c=strc " "

现在已知   a=100,b=150,c=20
求一个函数需要生成如下代码

"http://www.myside.com/default.aspx?a=100&b=150&c=20 "

------解决方案--------------------
//为什么不这样?
int a = 100;
int b = 150;
int c = 20;

string templete = @ "http://www.myside.com/default.aspx?a={0}&b={1}&c={2} ";
Text = string.Format(templete, a, b, c);

------解决方案--------------------
//这样可以吗?
string templete = @ "http://www.myside.com/default.aspx?a= <%a%> &b= <%b%> &c= <%c%> ";
templete = templete.Replace( " <%a%> ", a.ToString());
templete = templete.Replace( " <%b%> ", b.ToString());
templete = templete.Replace( " <%c%> ", c.ToString());

------解决方案--------------------
public string formatStr(string query, string obstruct)
{
if (!query.Contains(obstruct))
return string.Empty;

StringBuilder sbStr = new StringBuilder();
int startPosition = 0;
int endPosition = 0;

startPosition = query.IndexOf(obstruct, 0, query.Length);

if (startPosition <= 0)
return string.Empty;

endPosition = query.IndexOf( "& ", (startPosition + obstruct.Length));

if (endPosition <= 0)
{
endPosition = query.Length;
}

sbStr.Append(query.Substring((startPosition + obstruct.Length), (endPosition - (startPosition + obstruct.Length)))); ///(j+obstruct.Length),i-j)

return sbStr.ToString();
}