如何用新值替换{}内的字符串

时间:2014-12-29 10:11:02

标签: c#

string vehicleno="kl-12-22222";
DateTime dt = DateTime.Now;
string location = "Trivandrum";

我有一个来自数据库的字符串     string s =" (车号)在{Location Name}的{Time}偏离了GeoFence。";

我该如何展示

kl-12-11111 has deviated from GeoFence at 12/29/2014 in Trivandrum 
在C#中

3 个答案:

答案 0 :(得分:1)

将字符串输出放入您想要显示它的输出方法中(不知道您是控制台应用程序还是winforms或其他任何东西)

string output = String.Format(  "{0} has deviated from GeoFence at {1} in {2}",vehicleno,dt.ToString(),location )

答案 1 :(得分:1)

您可以使用String.Format方法,例如

int vehicleNumber = 123;
DateTime time = DateTime.Now;
string locationName = "here";
string text = string.Format("{0} has deviated from GeoFence at {1} in {2}", vehicleNumber.ToString(), time.ToString("mm/dd/yyyy"), locationName);

答案 2 :(得分:0)

如果您可以为模板使用不同的字符串,则可以使用以下内容:

string formattedText = string.Format(
    "{0} has deviated from GeoFence at {1} in {2}", 
    vehicleno, 
    dt.ToString("MM/dd/yyyy"), 
    location);

或者,您可以使用模板将Replace()调用链接在一起:

string formattedText = s.Replace("{Vehicle No}", vehicleno).Replace(...).Replace(...);