我可以像这样使用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";
答案 0 :(得分:3)
没有
是;只需构建一个数组,然后将该数组传递给String.Format
(this是您将使用的特定重载):
object[] values = new object[2];
values[0] = ...;
values[1] = ...;
String.Format(someString, values);
答案 1 :(得分: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);
}
答案 2 :(得分: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
答案 3 :(得分: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()));