连接字符串的最佳方式
本文关键字:方式 最佳 字符串 连接 | 更新日期: 2023-09-27 18:01:05
String outputFile = String.Format("{0}'t{1}'t{2}'t{3}'r'n", x.url, x.company, x.country, x.vendor,);
if (client.cf.is_cis == true)
{
outputFile = String.Format("{0}'r'n", x.cis);
}
if (client.cf.is_firmographic == true)
{
outputFile = String.Format("{0}'t{1}'r'n", x.revenue, x.employee);
}
writerCustomerTxt.Write(outputFile);
我试图输出一组字符串,但很明显,对于上面的代码,如果if语句中的任何一个为true,则输出将被覆盖。我相信字符串串联就是解决这个问题的方法。最有效的方法是什么?
要准确地得到您的要求有点困难,但使用StringBuilder
来构建字符串,这将起作用:
StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0}'t{1}'t{2}'t{3}'r'n",
x.url, x.company, x.country, x.vendor);
if (client.cf.is_cis == true)
{
builder.AppendFormat("{0}'r'n",
x.cis);
}
if (client.cf.is_firmographic == true)
{
builder.AppendFormat("{0}'t{1}'r'n",
x.revenue, x.employee);
}
writerCustomerTxt.Write(builder.ToString());
连接字符串的最简单方法是使用+=
运算符:
String outputFile = String.Format("{0}'t{1}'t{2}'t{3}'r'n", x.url, x.company, x.country, x.vendor);
if (client.cf.is_cis == true)
{
outputFile += String.Format("{0}'r'n", x.cis);
}
if (client.cf.is_firmographic == true)
{
outputFile += String.Format("{0}'t{1}'r'n", x.revenue, x.employee);
}
writerCustomerTxt.Write(outputFile);
顺便说一句,如果您没有在这里传递任何参数,那么您可以删除,
:
String.Format("{0}'t{1}'t{2}'t{3}'r'n", x.url, x.company, x.country, x.vendor, );
^^^