我有一个 WPF 文本框,用户可以在其中键入数字。现在我正在寻找一种字符串格式,它可以将 TextBox 数字每 3 个点分开(如 0,0),但我想要用 Slash 分隔文本或 Back Slash 或其他字符。而且我们不知道我们的数字有多少分。
我正在搜索字符串格式,而不是 Linq 解决方案等。我读过 Microsoft help 但找不到任何方法。
样本 = 123456789 ==> 123/456/789(好)--- 123,456,789(坏)
更新:
谢谢大家,但我正在搜索类似 stringformat= {}{0:0,0} 等的东西。我的意思是不想使用像 regex、replace 或 linq 或任何 c# 代码这样的字符串函数。我想使用 {#,#} 等字符串。请参阅我帖子中的 Microsoft 链接 我需要为我的问题创建一个字符串。
请您参考如下方法:
由于 OP 坚持使用 String.Format:
string input; //the input of your textbox
int temp = int.Parse(input); //parse your input into an int
//the Format() adds the decimal points, the replace replaces them with the /
string output = String.Format("{0:0,0}", temp).Replace('.', '/');
此处重要的一步是将文本框的文本转换为整数,因为这简化了使用 String.Format() 插入小数点的过程。 当然,你必须确保你的文本框在解析时是一个有效的数字,否则你可能会得到一个异常。
编辑
所以...您有一些动态长度 数字并希望使用静态 格式字符串(如正则表达式、字符串替换、ling 或任何 c#根本没有代码(!)是不行的)?这是不可能的。 你必须有一些动态代码在某处创建格式字符串。
无需再次引用正则表达式或字符串替换,这里有一些代码可根据您的输入数字创建格式字符串。
这样您就只有一个 String.Format() 调用。或许您可以将用于创建格式字符串的算法放在其他地方,然后在您需要的任何地方调用它。
string input; //the input of your textbox
int temp = int.Parse(input); //parse your input into an int
string customString = "{0:";
string tempS = "";
for (int i = 0; i < input.Length; i++)
{
if (i % 3 == 0 && i != 0)
{
tempS += "/";
}
tempS += "#";
}
tempS = new string(tempS.Reverse().ToArray());
customString += tempS;
customString += "}";
string output = String.Format(customString, temp));
