我有一个鼠标移动坐标,
例如:
s = string.Format("{0:D4},{1:D4}", nx, ny);
the result s is "0337,0022"
问题是如何只在前面显示两位数字?
我想得到:
s is "03,00"
这是另一个例子:
s = "0471,0306"
我想成为:
s = "04,03"
当坐标为“-”时
例子
s = "-0471,0306"
我想成为:
s = "-04,03"
我有一个鼠标移动坐标,
例如:
s = string.Format("{0:D4},{1:D4}", nx, ny);
the result s is "0337,0022"
问题是如何只在前面显示两位数字?
我想得到:
s is "03,00"
这是另一个例子:
s = "0471,0306"
我想成为:
s = "04,03"
当坐标为“-”时
例子
s = "-0471,0306"
我想成为:
s = "-04,03"
s =string.Format("{0},{1}",
string.Format("{0:D4}", nx).Substring(0,2),
string.Format("{0:D4}", ny).Substring(0,2));
只需在逗号上拆分字符串,然后将每个部分的前两个字符子串起来,如下所示:
string result = String.Empty;
string s = String.Format("{0:D4},{1:D4}", nx, ny);
string[] values = s.Split(',');
int counter = 0;
foreach (string val in values)
{
StringBuilder sb = new StringBuilder();
int digitsCount = 0;
// Loop through each character in string and only keep digits or minus sign
foreach (char theChar in val)
{
if (theChar == '-')
{
sb.Append(theChar);
}
if (Char.IsDigit(theChar))
{
sb.Append(theChar);
digitsCount += 1;
}
if (digitsCount == 2)
{
break;
}
}
result += sb.ToString();
if (counter < values.Length - 1)
{
result += ",";
}
counter += 1;
}
注意:这适用于s
字符串中任何数量的逗号分隔值。
假设 nx 和 ny 是整数
s = nx.ToString("D4").Substring(0,2) // leftmost digits
+ ny.ToString("D4").Substring(0,2) // leftmost digits
"D4" 确保字符串的大小必须足够子字符串边界
我会这样做:
Func<int, string> f = n => n.ToString("D4").Substring(0, 2);
var s = string.Format("{0},{1}", f(nx), f(ny));
在使用 Substring 之前检查数字。
var s1 = nx.ToString();
var s2 = ny.ToString();
// Checks if the number is long enough
string c1 = (s1.Count() > 2) ? s1.Substring(0, 2) : s1;
string c2 = (s2.Count() > 2) ? s2.Substring(0, 2) : s2;
Console.WriteLine("{0},{1}",c1,c2);