简体   繁体   English

需要格式化字符串

[英]Need to format a string

I have to format the addresses of my application in to a format like below using a single string. 我必须使用单个字符串将应用程序的地址格式化为以下格式。

1421 COUNTRY CLUB RD    
PO BOX 953  
CAMDEN  
USA

But I have different columns in my table for each fields. 但是我的表中每个字段都有不同的列。

在此处输入图片说明

I have to format them into a single string and display like this.. 我必须将它们格式化为单个字符串并像这样显示。

Address1
Address2
Address3
City
ZIPCode
County
State
Country

So far what I have done is I format them into a string in my Model 到目前为止,我要做的是在模型中将它们格式化为字符串

 public string DisplayShippingAddress
        {
            get { return string.Format("{0} {1} {2} {3} {4} {5} {6} {7}", this.Address1, this.Address2, this.Address3,this.City,this.ZIPCode, this.County,this.State,this.Country); }
        }

But I get a single line string.I need to format it just like above 但是我得到了一个单行字符串,我需要像上面一样格式化

To split a string across lines, you just use the newline character: '\\n' 要跨行拆分字符串,只需使用换行符:'\\ n'

get { return string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}", this.Address1, this.Address2, this.Address3,this.City,this.ZIPCode, this.County,this.State,this.Country); }

Most controls aren't multiline by default, so make sure to turn it on in whatever you are using to output this. 默认情况下,大多数控件不是多行的,因此请确保在用于输出此控件的任何控件中将其打开。

Since it is one line per value I would look at doing it like this: 因为每个值只有一行,所以我会这样看:

public string DisplayShippingAddress
{
    get
    {
        return String.Join(Environment.NewLine, new []
        {
            this.Address1, this.Address2, this.Address3,
            this.City, this.ZIPCode, this.County,
            this.State, this.Country
        });
    }
}
public string DisplayShippingAddress
    {
        get { return string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}", this.Address1, this.Address2, this.Address3,this.City,this.ZIPCode, this.County,this.State,this.Country); }
    }

用户环境。换行符,它将在您需要的任何位置插入新行。

var addressFormat = this.Address1 +Environment.Newline+this.Address2+Environment.Newline;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM