将字符串中的变量与“@";象征
本文关键字:quot 象征 字符串 变量 | 更新日期: 2023-09-27 18:27:25
给定这个多行字符串:
string strProviderJSON = @"
{
""npi"":""1111111111"",
""name"":""DME Clearinghouse"",
""email"":""my@doc.como"",
""contactName"":""Sally Smith"",
""fax"":"""",
""address"":{
""country"":""United States"",
""street1"":""27787 Dequindre Apt 616"",
""street2"":"""",
""city"":""Madison Heights"",
""state"":""MI"",
""zipCode"":""32003""
},
""phone"":""(904) 739-0300"",
""contactPhone"":""(904) 739-0300""
}
";
如何连接其中的变量?我试过这个,但一直得到一个错误:
string strTest = "1111111111";
string strProviderJSON = @"
{
""npi"":""" + strTest + """,
""name"":""DME Clearinghouse"",
""email"":""my@doc.como"",
""contactName"":""Sally Smith"",
""fax"":"""",
""address"":{
""country"":""United States"",
""street1"":""27787 Dequindre Apt 616"",
""street2"":"""",
""city"":""Madison Heights"",
""state"":""MI"",
""zipCode"":""32003""
},
""phone"":""(904) 739-0300"",
""contactPhone"":""(904) 739-0300""
}
";
在下一个字符串文字的开头附加另一个@
字符。
...
""npi"":""" + strTest + @"""
""name"": ""DME Clearinghouse"",
...
对于字符串串联,您应该使用string.Format()方法,因为正常串联会在内存中创建多个字符串,因此string.Formation()将以简单的方式帮助您插入变量。
示例:
String s = "111111";
String finalString = String.Format(@""npi"":""{0}"",s);
这是针对单行的(可以使用多行,但不可读)。现在,对于多行,您可以使用StringBuilder类,该类为我们提供了许多函数,如Append()、AppendFormat(),因此使用它可以获得可读的代码
示例:
StringBuilder tempString = new StringBuilder();
tempString.Append("{'n");
tempString.AppendFormat(@"""npi"":""{0}"",'n", npiString);// npiString is a variable
tempString.AppendFormat(@"""name"":""{0}"",'n", nameString);// nameString is a variable
.....
// you should add variables like this
// at the end you can store final string by using following
String finalString = tempString.ToString();
注意:我在String中没有多次使用这些",所以不确定,但添加变量应该由StringBuilder完成。
希望它能帮助你实现目标。