2012-12-06 19 views
26

Vorrei elencare un string e invece di restituirlo chars Mi piacerebbe avere la variabile iterativa di tipo string. Questo probabilmente non è possibile che il tipo iterativo sia un string, quindi qual è il modo più efficace per scorrere questa stringa?Come posso convertire un singolo carattere in una stringa?

Devo creare un nuovo oggetto string con ogni iterazione del ciclo o posso eseguire un cast in qualche modo?

String myString = "Hello, World"; 
foreach (Char c in myString) 
{ 
    // what I want to do in here is get a string representation of c 
    // but I can't cast expression of type 'char' to type 'string' 
    String cString = (String)c; // this will not compile 
} 

risposta

32

Utilizzare la .ToString() Metodo

String myString = "Hello, World"; 
foreach (Char c in myString) 
{ 
    String cString = c.ToString(); 
} 
+2

Considerare l'uso dei tipi C# 'stringa' e' carattere' invece dei tipi CLR. Lo stesso alla fine, ma probabilmente più corretto in C#. – andleer

+0

@andleer Hai ragione, ho appena modificato il codice di esempio di OP per mostrare il metodo ToString. –

+1

Il commento era diretto a lui, non tu. Nessun problema. – andleer

4

Sembra che la cosa più ovvia da fare è questa:

String cString = c.ToString() 
+10

Penso che tu abbia risposto alla tua stessa domanda. – seand

1

Creare una nuova stringa dal char.

String cString = new String(new char[] { c }); 

o

String cString = c.ToString(); 
-1

Hai provato:

String s = new String(new char[] { 'c' });

+1

Non c'è ctor che vuole solo char –

+0

dispiaciuto, a cura e testati – trebuchet

0
String cString = c.ToString(); 
5

Hai due opzioni. Creare un oggetto string o chiamare il metodo ToString.

String cString = c.ToString(); 
String cString2 = new String(c, 1); // second parameter indicates 
            // how many times it should be repeated 
1

Creare un metodo di estensione:

public static IEnumerable<string> GetCharsAsStrings(this string value) 
{ 
    return value.Select(c => 
      { 
       //not good at all, but also a working variant 
       //return string.Concat(c); 

       return c.ToString(); 
      }); 
} 

e ciclo attraverso le stringhe:

string s = "123456"; 
foreach (string c in s.GetCharsAsStrings()) 
{ 
    //... 
} 
+0

wow questo è così goffo ... –

0

Perché non questo codice? Non sarà più veloce?

string myString = "Hello, World"; 
foreach(char c in myString) 
{ 
    string cString = new string(c, 1); 
} 
1

Con C# 6 interpolazione:

char ch = 'A'; 
string s = $"{ch}"; 

Questo fa la barba pochi byte. :)

Problemi correlati