在C#中为我的字符串添加' - '

Shw*_*eta 2 c#

我有一个"123456789"形式的字符串.在屏幕上显示时我想将其显示为123-456-789.请告诉我如何为每3个数字添加" - ".提前致谢.

Mar*_*ers 6

你可以使用string.Substring:

s = s.Substring(0, 3) + "-" + s.Substring(3, 3) + "-" + s.Substring(6, 3);
Run Code Online (Sandbox Code Playgroud)

或正则表达式(ideone):

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


ros*_*dia 5

我会继续提供Regex基础解决方案:

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

正则表达式分解如下:

(        // 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"
)        
Run Code Online (Sandbox Code Playgroud)

"$1-"替换字符串意味着每当对上述图案的匹配,则用相同的($ 1份),然后进行替换它-.所以"123456789",它会匹配123456,而不是789因为它是在字符串的结尾.然后用它替换它们,123-456-给出最终结果123-456-789.