Come posso convertire un tipo di dati int
in un tipo di dati string
in C #?
string myString = myInt.ToString();
string s = i.ToString(); string s = Convert.ToString(i); string s = string.Format("{0}", i); string s = $"{i}"; string s = "" + i; string s = string.Empty + i; string s = new StringBuilder().Append(i).ToString();
Nel caso in cui si desideri la rappresentazione binaria e si è ancora ubriachi dalla festa dell’ultima notte:
private static string ByteToString(int value) { StringBuilder builder = new StringBuilder(sizeof(byte) * 8); BitArray[] bitArrays = BitConverter.GetBytes(value).Reverse().Select(b => new BitArray(new []{b})).ToArray(); foreach (bool bit in bitArrays.SelectMany(bitArray => bitArray.Cast().Reverse())) { builder.Append(bit ? '1' : '0'); } return builder.ToString(); }
Nota: Qualcosa sul non gestire endianness molto bene …
Modifica: se non ti dispiace sacrificare un po ‘di memoria per la velocità, puoi utilizzare di seguito per generare un array con valori di stringa precalcolati:
static void OutputIntegerStringRepresentations() { Console.WriteLine("private static string[] integerAsDecimal = new [] {"); for (int i = int.MinValue; i < int.MaxValue; i++) { Console.WriteLine("\t\"{0}\",", i); } Console.WriteLine("\t\"{0}\"", int.MaxValue); Console.WriteLine("}"); }
int num = 10; string str = Convert.ToString(num);
Si suppone che il metodo ToString di qualsiasi object restituisca una rappresentazione stringa di quell’object.
int var1 = 2; string var2 = var1.ToString();
string str = intVar.ToString();
In alcune condizioni, non è necessario utilizzare ToString()
string str = "hi " + intVar;
o:
string s = Convert.ToString(num);
Più avanti sulla risposta di @ Xavier, ecco una pagina che fa un rapido confronto tra diversi modi per effettuare la conversione da 100 iterazioni fino a 21.474.836 iterazioni.
Sembra un bel legame tra:
int someInt = 0; someInt.ToString(); //this was fastest half the time //and Convert.ToString(someInt); //this was the fastest the other half the time
using System.ComponentModel; TypeConverter converter = TypeDescriptor.GetConverter(typeof(int)); string s = (string)converter.ConvertTo(i, typeof(string));
Nessuna delle risposte ha indicato che il metodo ToString()
può essere applicato alle espressioni intere
Debug.Assert((1000*1000).ToString()=="1000000");
anche ai letterali interi
Debug.Assert(256.ToString("X")=="100");
Sebbene i letterali interi come questo siano spesso considerati come uno stile di codifica errato ( numeri di Magic ), alcuni casi possono essere utili quando questa funzione è utile …
string s = “” + 2;
e puoi fare cose carine come: stringa s = 2 + 2 + “tu” che sarà “4 tu”