Is it possible to replace the index number with a string in String.Format in C #?

Can it be used string.Formatas follows?

1) Replace the number with a string

string sample = "Hello, {name}";

//I want to put a name string into {name}, is it possible?

* * 2) Is it possible to sequentially add lines for a string template

string sample = "My name is {0}, I am living in {1} ...";

// put {0} value
// and put {1} value separately

ex)
sample[0] = "MIKE";
sample[1] = "Los Anageles";
+3
source share
4 answers

1

string sample1 = "Hello, {name}";
Console.WriteLine(sample1.Replace("{name}", "John Smith"));

2

string sample2 = "My name is {0}, I am living in {1} ..."; 
var parms = new ArrayList();
parms.Add("John");
parms.Add("LA");
Console.WriteLine(string.Format(sample2, parms.ToArray()));
+1
source
  • No

  • Yes; just create an array, then pass that array to String.Format( this is the specific overload you will use):

    object[] values = new object[2];
    values[0] = ...;
    values[1] = ...;
    String.Format(someString, values);
    
+3
source

# 2:

    [Test]
    public void Passing_StringArray_Into_StringFormat()
    {
        var replacements = new string[]
            {
                "MIKE",
                "Los Angeles"
            };
        string sample = string.Format("My name is {0}, I am living in {1} ...", replacements);

        Assert.AreEqual("My name is MIKE, I am living in Los Angeles ...", sample);
    }
+2

All Articles