繁体   English   中英

如何在C#中的特定位置替换字符串?

[英]How to replace a string at a particular postion in c#?

    string q1 = "What [replace string] years? ";

In the above question I want to replace "years of study" with `model.values` 
so my required output should be as:

    string q1 = "What [replace string] years?";

其中“ 2013,2014”将来自数据库。

因此,我需要将值附加到静态问题,这些值将来自使用mvc模型的数据库。

我如何在特定位置替换字符串,我在那儿有任何建议,它将对我有所帮助。

使用string.Format()

将您的q1声明更改为此

string q1 = "What type of legal entity was the Company during the {0} tax years? ";

然后格式化字符串

var q2 = string.Format(q1, <replacement  string>);

其中<replacement string>是您要替换的值

所以,

var q2 = string.Format(q1, model.Values);

请参阅MSDN上的文档

您可以使用$ c#6.0功能

$"What type of legal entity was the Company during the {Model.values} tax years? "

尝试这样:-

  string q2=  String.Format("What type of legal entity was the Company during the {0} tax years? ", YourModelName.Years);

您可以尝试使用string.Replace

string q1 = "What type of legal entity was the Company during the [years of the study] tax years? ";
q1 = q1.Replace("[years of the study]", someValue.ToString());

但是,这不是一个很好的做法。 如其他建议那样,使用string.Format更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM