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

时间:2017-04-19 13:52:51

标签: c# asp.net-mvc

    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模型的数据库。

如何替换特定位置的字符串我坚持在那里有任何建议,它会帮助我提前感谢。

4 个答案:

答案 0 :(得分:2)

使用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上的documentation

答案 1 :(得分:1)

您可以使用$ c#6.0功能

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

答案 2 :(得分:0)

尝试这样: -

def set_membership(x, interesting_numbers):
    b = np.sort(list(interesting_numbers))
    idx = np.searchsorted(b, x)
    idx[idx==b.size] = 0
    return b[idx] == x

答案 3 :(得分:0)

您可以尝试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更好。