是否可以在 C# 中的字符串格式中将索引号替换为字符串

本文关键字:字符串 索引 替换 格式 是否 | 更新日期: 2023-09-27 18:31:36

我可以像这样使用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";

是否可以在 C# 中的字符串格式中将索引号替换为字符串

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

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

以下是您完成 #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);
    }
您可以使用

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

1:

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

阿拉伯数字:

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