在C#中使用字符串格式化程序在大括号之间添加字符串

Add strings between curly braces using string formatter in c#
2021-07-21
  •  译文(汉语)
  •  原文(英语)

我需要合并两个字符串值,并且这些值应该放在花括号之间,我试图将字符串格式定义为常量并传递字符串值,我尝试了多种格式,但始终会收到Invalid Input Parameter异常.是否可以使用字符串格式化程序执行以下操作?如果那又如何?

private const string formatString = "'{'{0}'}''{'{1}'}'";

string str1 = "John";
string str2 = "John@Xmail.com";

string resultString = string.Format(formatString, str1, str2);

预期产量

{John}{John@Xmail.com}

解决过程1

您必须使用双花括号将其转义.

private const string formatString = "{{{0}}}{{{1}}}";
解决过程2

您必须逃脱,{然后}才能使用它们string.Format

private const string formatString = "{{{0}}}{{{1}}}";

I have a requirement to concat two string values and these values should be placed between curly braces, I'm trying to define string format as a constant and passing the string values, I have tried many formats but always am getting Invalid Input Parameter exception. Is that possible to do the following using string formatter ? if then how ?

private const string formatString = "'{'{0}'}''{'{1}'}'";

string str1 = "John";
string str2 = "John@Xmail.com";

string resultString = string.Format(formatString, str1, str2);

Expected Output

{John}{John@Xmail.com}

Solutions1

You must escape it using double curly braces.

private const string formatString = "{{{0}}}{{{1}}}";
Solutions2

You have to escape { and } in order to use them on string.Format

private const string formatString = "{{{0}}}{{{1}}}";
转载于:https://stackoverflow.com/questions/17413523/add-strings-between-curly-braces-using-string-formatter-in-c-sharp

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入