Is it possible in C # when you enter the string “string”, for example: “Dog” – divide it into letters “C”, “o”, “b”, “a”, “k”, “a”. I know from the “Split” function, but there it is necessary to specify the place for the division, but I need to direct each character and space too!
Answer 1, authority 100%
The string
class has a special ToCharArray
method that returns an array of characters. Also string
implements IEnumerable & lt; char & gt;
, so we can use the Linq extension method ToArray
. Choose whichever you like (but I suspect that the first can work faster, because the string length is known, and the second is a more universal method and works for any sequences):
string s = "string";
char [] a = s.ToCharArray ();
char [] b = s.ToArray ();
Well, if you do not need to change the data, but only read, you can use the indexer: Console.WriteLine (s [0]);
If you want to edit a string character by character, then get a character array as described above, edit any elements in it and get a string from the final array (string
has a constructor that accepts an array of characters):
string s2 = new string (a);
Instead of an array, you can use the StringBuilder
class – it represents a mutable string, its indexer supports both reading and writing:
string s1 = "string";
StringBuilder sb = new StringBuilder (s1);
sb [0] = 'b';
sb [1] = 'o';
string s2 = sb.ToString ();
Console.WriteLine (s2);
Answer 2, authority 83%
Alternatively:
string str = "Dog";
foreach (char c in str)
{
Console.WriteLine (c);
}
Console.ReadLine ();