È necessario convertire la stringa in un numero a fare il test per meno di 10:
// this will throw an exception if the string does not contain a number
int unreadzNumber = int.Parse(Unreadz);
Se si è certi che la stringa contenga esattamente una cifra e nient'altro, è sufficiente verificare se ha una lunghezza 1:
bool isLessThanTen = Unreadz.Length == 1;
Si può fare la formattazione in una varietà di modi diversi:
// 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
io preferisco la seconda perché rende il formato più chiaro e più facile da mantenere e non richiede il confronto.
Quindi, si ottiene:
string Unreadz = "0";
while (true)
{
Unreadz = CheckMail();
int unreadzNumber = int.Parse(Unreadz);
port.Write(string.Format("{0:00}", unreadzNumber));
}
fonte
2011-08-22 13:52:58
uso del Unreadz.length, se siete interessati in lunghezza o analizza in un numero intero come Int32.Parse (unreadz) se si desidera che il valore numerico memorizzato all'interno della stringa –