Reputation: 970
Lets say that I have a string that is mostly complete. In the middle of it is an entry that is variable - for example:
string speech = @"I am very"
variable"and I need some lighter clothes"
Assuming I don't want to create another string to handle that last part of that sentence, how do I place one of many words for "hot" in place of variable?
My pseudo theory would go something like this:
string speech = @"I am very " + &antonym + " and I need some lighter clothes";
public string putTheSentenceTogether(string antonym)
{
return speech(antonym);
}
Can this be done in C#? Or an any other way that doesn't require me to split speech
up?
Upvotes: 0
Views: 51
Reputation: 48600
How about you do
string speech = @"I am very {0} and I need some lighter clothes";
public string PutTheSentenceTogether(string antonym)
{
return string.Format(speech, antonym);
}
Or you can do (in C# 6.0 i.e. VS 2015 and later)
public string PutTheSentenceTogether(string antonym)
{
return $"I am very {antonym} and I need some lighter clothes";
}
Upvotes: 4
Reputation: 1048
This will work using string interpolation:
public string putTheSentenceTogether(string antonym)
{
return $"I am very {antonym} and I need some lighter clothes";
}
Or using string.Format
public string putTheSentenceTogether(string antonym)
{
return string.Format("I am very {0} and I need some lighter clothes", antonym);
}
Provided you want to declare the string outside of the method, you could do
string speech = "I am very {0} and I need some lighter clothes";
public string putTheSentenceTogether(string antonym)
{
return string.Format(speech, antonym);
}
Upvotes: 2
Reputation: 5552
Using C# 6.0 or later, try:
string myAntonym = "hot";
string speech = $"I am very {myAntonym} and I need some lighter clothes";
Upvotes: 4