我有一個像123456789的數字。我想顯示123-45-6789這樣的數字。我怎樣才能在asp.net中用C#實現這一點?帶連字符分隔符的數字(123456789到123-45-6789)
此編號以varchar格式存儲在數據庫中。我只是想用恰當的炒作在標籤中顯示數字。
我有一個像123456789的數字。我想顯示123-45-6789這樣的數字。我怎樣才能在asp.net中用C#實現這一點?帶連字符分隔符的數字(123456789到123-45-6789)
此編號以varchar格式存儲在數據庫中。我只是想用恰當的炒作在標籤中顯示數字。
使用基本號碼,格式:
yourNumber.ToString("###-##-####");
更新:
好吧,如果你已經擁有了它作爲一個字符串,你可以把它分解,並添加連字符:
var result = str.Substring(0,3) + "-"
+ str.Substring(3,2) + "-"
+ str.Substring(5);
...或在secont認爲,也許String.Insert()更簡單:
// insert "-" after position 3, then after position 6 in the returned string.
result = str.Insert(3, "-").Insert(6, "-");
它顯示錯誤,因爲num已經是字符串。'string.ToString(System.IFormatProvider)'的最佳重載方法匹配有一些無效參數 – Golda
只要你可以使用。
var outputString = yourString.Insert(3,"-").Insert(6,"-");
試試這個...
Regex.Replace("987654321", @"(\d{3})(\d{2})(\d{4})", "$1-$2-$3");
你有這樣的格局?我沒有看到這一個。 –
不可以。我怎樣才能實現這種使用模式? – Golda
你誤解了我。例如;如果你的號碼是'987654321',你的結果應該是'987-65-4321'?你想將它們分開爲「3位 - 2位 - 4位」? –