您需要将字符串转换为一个数字,以不到10做了测试:
// this will throw an exception if the string does not contain a number
int unreadzNumber = int.Parse(Unreadz);
如果您确定该字符串只包含一个数字而没有其他字符,您可以测试它是否具有长度1:
bool isLessThanTen = Unreadz.Length == 1;
你可以在各种不同的方式格式化:
// 1: just stick a zero before it
string formatted = string.Format("0{0}", unreadzNumber);
// 2: use a special format string to use at least two digits
string formatted = string.Format("{0:00}", unreadzNumber);
// 3: pad the string with zeros to the left
string formatted = Unreadz.PadLeft(2, '0');
// 4: manually concatenate with "0"
string formatted = "0" + Unreadz;
// and probably others
我更喜欢第二个,因为它使格式更清晰,更易于维护,并且不需要比较。
所以,你会得到:
string Unreadz = "0";
while (true)
{
Unreadz = CheckMail();
int unreadzNumber = int.Parse(Unreadz);
port.Write(string.Format("{0:00}", unreadzNumber));
}
使用Unreadz.length如果你有兴趣的长度或解析它像Int32.Parse(unreadz)一个整数,如果你想存储的字符串 –