2011-11-09 42 views
2

我有一個字符串形式爲「123456789」。 在屏幕上顯示它時,我想將其顯示爲123-456-789。 請讓我知道如何添加「 - 」每3個數字。 在此先感謝。在C#中的字符串中添加' - '

+2

這是百達9個數字,也可以是無限的? – Gleeb

回答

5

我會繼續前進,給Regex基礎的解決方案:

string rawNumber = "123456789"; 
var formattedNumber = Regex.Replace(rawNumber, @"(\d{3}(?!$))", "$1-"); 

該正則表達式分解如下:

(  // Group the whole pattern so we can get its value in the call to Regex.Replace() 
    \d  // This is a digit 
    {3} // match the previous pattern 3 times 
    (?!$) // This weird looking thing means "match anywhere EXCEPT the end of the string" 
)   

"$1-"替換字符串意味着每當對上述圖案的匹配,則用相同的($ 1部分),接着是-替換它。因此,在"123456789"中,它將匹配123456,但不匹配789,因爲它位於字符串的末尾。然後用123-456-替換它們,給出最終結果123-456-789

+0

非常感謝:) – Shweta

6

您可以使用string.Substring

s = s.Substring(0, 3) + "-" + s.Substring(3, 3) + "-" + s.Substring(6, 3); 

或正則表達式(ideone):

s = Regex.Replace(s, @"\d{3}(?=\d)", "$0-"); 
0

您可以使用循環也如果字符串長度不固定到9倍的數字如下

string textnumber = "123456789"; // textnumber = "123456789" also it will work 
      string finaltext = textnumber[0]+ ""; 
      for (int i = 1; i < textnumber.Length; i++) 
      { 
       if ((i + 1) % 3 == 0) 
       { 
        finaltext = finaltext + textnumber[i] + "-"; 
       } 
       else 
       { 
        finaltext = finaltext + textnumber[i]; 
       } 
      } 
      finaltext = finaltext.Remove(finaltext.Length - 1);