0

I'm declaring a string at initialisation as follows

string a = string.Format("Hello {0}", "World.");

Is there a way to subsequently replace the zeroth argument for something else?

If there's no obvious solution, does anybody know of a better way to address the issue. For context, at initialisation I create a number of strings. The text needs to be updated as the program proceeds. I could create a structure comprising an array of strings and an array of objects and then build the final string as required, but this seems ugly, particularly as each instance could have a different number of arguments.

For example,

public class TextThingy
{
   List<String> strings;
   List<String> arguments;

   ...

   public string ToString()
   {
      return strings[0] + arguments [0] + strings [1] ...
   }

I've tried this, but to no avail.

string b = string.Format(a, "Universe.");

I guess that the argument {0} once populated is then baked into the string that one time.

4
  • learn.microsoft.com/en-us/dotnet/standard/base-types/… Commented Dec 21, 2022 at 14:27
  • string b = string.Format("Hello {0}", "Universe.");? Commented Dec 21, 2022 at 14:28
  • string fmt = "Hello {0}"; then string a = string.Format(fmt, "World"); then string b = string.Format(fmt, "Universe"); Commented Dec 21, 2022 at 14:30
  • 1
    Does this answer your question? C# Format String Commented Dec 21, 2022 at 14:31

2 Answers 2

3

You could move the format string to a variable like this? Would that work? If not, please add some more info for us.

string fmt = "Hello {0}";

string a = string.Format(fmt, "World.");

string b = string.Format(fmt, "Universe.");
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect - thanks. I didn't realise it could just be left empty initially.
0

try string replace, like ...

StringBuilder sb = new StringBuilder("11223344");

string myString =
    sb
      .Replace("1", string.Empty)
      .Replace("2", string.Empty)
      .Replace("3", string.Empty)
      .ToString();

Comments

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.