surya koti
surya koti

Reputation: 5

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?";

where "2013,2014" will be coming from database .

So I need to append values to the static question ,the values will be coming from database using mvc models.

How to replace a string at a particular position i stuck there any suggestions it will help me thanks in advance.

Upvotes: 0

Views: 133

Answers (4)

dbrckovi
dbrckovi

Reputation: 121

You can try 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());

However, this is not a very good practice. Using string.Format, as others suggested is better.

Upvotes: 0

Pranav
Pranav

Reputation: 8871

Try Like This :-

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

Upvotes: 0

Azzy Elvul
Azzy Elvul

Reputation: 1438

You can use $ c# 6.0 feature

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

Upvotes: 1

Fran
Fran

Reputation: 6520

Use string.Format()

change you q1 declaration to this

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

Then format the string

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

with <replacement string> being the values you are substituting

So,

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

See the documentation on MSDN

Upvotes: 2

Related Questions