2011-11-09 116 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);