您需要將字符串轉換爲一個數字,以不到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)一個整數,如果你想存儲的字符串 –