使用String.Format格式化地址 [英] Using String.Format to format a Address

查看:99
本文介绍了使用String.Format格式化地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课,拥有街,PoBox,城市属性.其中一些可以具有空值.我想提供一种方法,以充分利用这些方法的作用,例如
街,
PoBox,
城市.

如何使用string.format创建此文件.当我使用此属性时,如果有任何属性为空,则会给出空行.

[edit]较小的可读性更正[/edit]

我的代码是这样的

I have a class with properties Street, PoBox, City. Some can have empty values from these. I want to give a method to take full address from those methods like
Street,
PoBox,
City.

How can I create this by using string.format. When I''m using this, if any property has empty it gives empty line.

[edit]Minor corrections for readability[/edit]

My code is like this

string street = "AAA";
string city = string.Empty;
string country = "SSS";

string add = string.Format("{0}\n{1}\n{2}",street, city, country);
Console.WriteLine(add);


结果:


Result:

AA

SSS


我的问题是,当城市为空时,街道和县之间会出现多余的线.


My problem is when city is empty, extra line comes between the street and county.

推荐答案

String.Format如果某些值不返回空字符串为空.例如:
String.Format won''t return an empty string if some of the values are null. For example:
string val1 = null;
string val2 = "Something";

string.Format("Test: {0}/{1}", val1, val2);


给出Test: /Something
所以也许您还有其他问题.使用调试器尝试隔离返回字符串为空的部分.


Gives Test: /Something
So perhaps you have some other problem. Using the debugger try to isolate the part where the return string is getting empty.


使用如下代码:

Use something like this:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
void AddLine(string value) {
   if (!string.IsNullOrEmpty(value))
      sb.AppendLine(value); 
}
void AddLines(string[] values) {
   foreach(value in values)
      AddLine(value); 
}

//...

AddLines(new string[] {street, city, country, phone, email, }); // :-)



—SA



—SA


尝试一下-

Try This--

string street = "AAA"; 
string city = string.Empty;
string country = "SSS";
string FullAddress=string.Format("{0}{1}{2}{3}{4}",street ,(string.IsNullorEmpty(street)?"":Enviornment.NewLine),city,(string.IsNullorEmpty(city)?"":Enviornment.NewLine),country)



--Pankaj



--Pankaj


这篇关于使用String.Format格式化地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆