在字符串中间插入变量值
在C#:如果我想创建这样的消息:“嗨我们有这些航class: 航classA,B,C,D。你想要哪一个”
只有粗体部分是动态的,我在运行时传递它的值,但它的左右部分是固定的。 我可以创建像LeftMessage +那些变量+ RightMessage来创建它。 但我想知道是否有一种方法可以同时完成所有操作,而无需创建两个单独的左右消息?
出于翻译目的,我将这些左右消息放在字符串资源中,所以现在我有两个单独的字符串资源。 有没有办法一次完成所有操作?
你可以使用string.Format
:
string template = "Hi We have these flights for you: {0}. Which one do you want"; string data = "A, B, C, D" string message = string.Format(template, data);
您应该从资源文件加载template
, data
是运行时值。
但是,如果要翻译成多种语言,请务必小心:在某些情况下,您需要使用不同语言的不同标记( {0}
)。
现在有了(C#6,Visual Studio 2015)更简洁的方法:字符串插值。
从另一个问题的答案 :
在C#6中,您可以使用字符串插值 :
string name = "John"; string result = $"Hello {name}";
在Visual Studio中为此突出显示的语法使其具有高可读性并检查所有标记。
使用String.Format
预C#6.0
string data = "FlightA, B,C,D"; var str = String.Format("Hi We have these flights for you: {0}. Which one do you want?", data);
C#6.0 – 字符串插值
string data = "FlightA, B,C,D"; var str = $"Hi We have these flights for you: {data}. Which one do you want?";
String.Format("Hi We have these flights for you: {0}. Which one do you want", flights);
编辑:您甚至可以单独保存“模板”字符串(例如,您可以将其存储在配置文件中并从那里检索),如下所示:
string flights = "Flight A, B,C,D"; string template = @"Hi We have these flights for you: {0}. Which one do you want"; Console.WriteLine(String.Format(template, flights));
EDIT2:哎呀,对不起我看到@DanPuzey已经提出了一些与我的EDIT非常相似的东西(但更好)
1您可以使用string.Replace
方法
var sample = "testtesttesttest#replace#testtesttest"; var result = sample.Replace("#replace#", yourValue);
2您也可以使用string.Format
var result = string.Format("your right part {0} Your left Part", yourValue);
3您可以使用Regex类