我有一个字符串形式为“123456789”。 在屏幕上显示它时,我想将其显示为123-456-789。 请让我知道如何添加“ - ”每3个数字。 在此先感谢。在C#中的字符串中添加' - '
2
A
回答
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"
中,它将匹配123
和456
,但不匹配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);
相关问题
- 1. 无法在C++中添加字符串
- 2. 在C++中添加两个字符串
- 3. 添加使用字符串^在C++中
- 4. 添加字符串在C#
- 5. 在C字符添加到字符串
- 6. 在C中添加一个字符串的字符
- 7. 在C++中的字符串之间添加一个字符
- 8. 在字符串中间添加字符
- 9. 在字符串中间添加字符
- 10. 如何将字符串添加到字符串数组中C
- 11. C++在字符串数组中添加任何字符
- 12. 在字符串(或Chararray)中添加一个字符c#
- 13. 在C#中的字符串之前添加@符号
- 14. 在字符串中添加换行符
- 15. C#加减字符串中的字符
- 16. 添加的字符串C#的数字
- 17. 在C++中添加一个字符串的所有数字
- 18. Java在字符串中添加数字
- 19. 在字符串中添加数字
- 20. jQuery在字符串中添加数字
- 21. 将一个换行符添加到C中的字符串中#
- 22. 将字符串添加到C中的字符指针
- 23. 如何添加字符到C#中的字符串
- 24. PHP中添加字符串
- 25. 在Linq中添加arraylist的字符串
- 26. 在PHP中的字符串内添加字符串
- 27. 在字符串中添加字符串的PHP引用
- 28. 添加在字符串中的整数在objective-c
- 29. 在C++中添加两个c字符串
- 30. 在Structure C++中添加值C字符串
这是百达9个数字,也可以是无限的? – Gleeb