3

我可以这样使用string.Format吗?

1 ) 将数字替换为字符串

string sample = "Hello, {name}";

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

* *2 ) 是否可以将字符串一一添加到字符串模板

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

4 回答 4

3
  1. 是的; 只需构建一个数组,然后将该数组传递给String.Format是您将使用的特定重载):

    object[] values = new object[2];
    values[0] = ...;
    values[1] = ...;
    String.Format(someString, values);
    
于 2012-04-19T16:41:32.897 回答
2

以下是您完成 #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);
    }
于 2012-04-19T16:43:44.417 回答
2

您可以使用 James Newton-King 的 FormatWith:http: //james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx

Phil Haack 有一篇关于它的好帖子:http: //haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx

于 2012-04-19T16:46:14.617 回答
1

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()));
于 2012-04-19T16:46:05.897 回答