2010-04-29 275 views
0

HI, 我想动态地使用C#连接字符串。我在XML文件中有本地化的字符串,这个字符串我想在运行时根据语言选择进行更新。
下面我指定了输入字符串和期望的输出字符串格式。字符串连接

EX: 
    *Input String:* 
     "The density of your %s gas at reference conditions of %s %s and %s %s is:" 
    *Expected Output String:* 
    "The density of your Helium gas at reference conditions of 20.01 g and 15.12 Kg is:" 

感谢

+1

也许你想用'{0}','{1}'等等,而不是'%s'。 – kennytm 2010-04-29 17:28:10

+0

这对我来说非常有用。谢谢 – Ravi 2010-04-30 05:49:02

+1

也许现在是时候接受至少几个问题的答案了? – Alex 2010-04-30 14:53:17

回答

6

您正在寻找string.Format

string output = string.Format(
"The density of your {0} gas at reference conditions of {1} {2} and {3} {4} is:", 
    gas, condition1, condition2, condition3, condition 4); 

不像C的printf功能,这依赖于在他们将取代该命令所提供的参数,string.Format要求您明确指出哪些参数去哪里。换句话说,{0}意味着第一个(0-索引)参数将在那里被替换。

您可以选择指定格式字符串(对数字和日期等有用),如下所示:{1:0.00}。这意味着第二个(索引1)元素的格式字符串为"0.00"(无论这可能意味着什么类型的问题)。

+0

这对我来说非常有用。谢谢 – Ravi 2010-04-30 05:53:48

+0

@Ravi:如果这解决了你的问题,请务必接受这个答案。你也可以考虑回到你的一些老问题上,并为这些问题做出答案。 – 2010-04-30 12:57:17

0
string output = "The density of your " + gas.ToString() + " gas at reference conditions of " + weightG.ToSTring() + "g and " + weightKg.ToSTring() + " Kg is:"; 
+1

这究竟是如何与本地化的字符串存储在一个XML文件? – cjk 2010-04-29 17:46:00