2013-09-26 62 views
0

我正在使用此代碼分隔下一行並給出空間。有沒有更簡單的代碼來分隔行?

String sms="Name:"+name+ System.getProperty ("line.separator")+System.getProperty 
    ("line.separator")+"ContactNumber:"+contactnumber+ System.getProperty 
    ("line.separator")+"Quantity:"+quantity+System.getProperty 
    ("line.separator")+"Number.of.Pcs:"+noofpieces+System.getProperty 
    ("line.separator")+"Date and Time:"+dateandtime 
    +System.getProperty ("line.separator")+"Delivary 
    Address:"+deliveryaddress; 
+2

你有沒有嘗試「\ n」? – 2013-09-26 12:57:17

+0

雅它沒有工作 – Deepak

回答

2

你可以使用一個StringBuilder實例,然後使用附加到StringBuilder新線運營商。例如:

StringBuilder sb = new StringBuilder(); 
sb.append("Name: ").append(name); 
sb.append("\n"); // for a new line. 

無論如何,我強烈建議您使用StringBuilder追加到一個非常大的字符串。

此外,您也可以使用System.lineSeparator();然而,這僅僅可以在Java中與JVM使用Java 7的工作,而不是在Android的(所以我肯定會檢查出來。)

+0

'System.lineSeparator()'是java 7,其中android不是。以前的Java版本使用'System.getProperty(「line.separator」)''。此屬性明確記錄爲Android http://developer.android.com/reference/java/lang/System.html#getProperty(java.lang.String) – njzk2

+0

@blackpanther如果您使用StringBuilder,則不應連接想要的值附加加號運算符,因爲這會創建另一個StringBuilder,然後附加它。例如在上面的例子中'sb.append(「Name:」+ name);'將被編譯爲'sb.append((new StringBuilder())。append(「Name:」).append(s).toString() );' – SubOptimal

1

String sms= "Name:" + name 
    + "\nContactNumber:" + contactnumber 
    + "\nQuantity:" + quantity 
    + "\nNumber.of.Pcs:" + noofpieces 
    + "\nDate and Time:" + dateandtime 
    + "\nDelivary Address:" + deliveryaddress; 
1

使用System.getProperty("line.separator")是這是一個很好的做法,因爲它會爲您提供可在其他平臺上重用的代碼。爲了簡化你的代碼,你可以使用TextUtils.join:

String sms = TextUtils.join(System.getProperty("line.separator"), 
    new String[] { 
     "Name:" + name , 
     "ContactNumber:" + contactnumber, 
     ...}); 
0

你也可以使用此解決方案

String format = "Name: %s%n%nContactNumber: %s%nQuantity: %s%nNumber.of.Pcs: %s%nDate and Time: %s%nDelivery Address: %s"; 
String sms = String.format(format, name, contactnumber, quantity, noofpieces, dateandtime, deliveryaddress); 

格式的佔位符,你在Javadoc中找到的解釋java.util.Formater

相關問題