0

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?

1
  • 2
    Have you tried it? There are many ways to concatenate a string in c#. Commented Mar 10, 2017 at 18:04

3 Answers 3

4

Using C# 6.0 or later, try:

string myAntonym = "hot";
string speech = $"I am very {myAntonym} and I need some lighter clothes";
Sign up to request clarification or add additional context in comments.

1 Comment

Although all of these examples work, this is the cleanest and shortest, I think, therefore I'm selecting it as the most appropriate answer.
4

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

Comments

2

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);
}

1 Comment

Interpolation in the first example needs to have a '$' symbol in place of the '@' symbol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.