C
C#9mo ago
aCasualNon

how do i split for example t he string "dog" into "d" "o" "g"

Help.
6 Replies
Kiel
Kiel9mo ago
.ToCharArray() is probably the simplest way to do it but...this will be a char[] and not string[] which is probably not what you want?
Pobiega
Pobiega9mo ago
Or just foreach over the string
Kiel
Kiel9mo ago
(will still iterate over chars but I digress)
Pobiega
Pobiega9mo ago
Depends on what the goal is here
oke
oke9mo ago
string testStr = "this is a string"

// Foreach loop
foreach (var c in testStr)
{
// Do something with 'c'
}

// For loop (should only be used when you NEED the index of the char, otherwise use foreach)
char[] tmpCArray = new char[testStr.Length];
for (int i = 0; i < testStr.Length; i++)
{
// Do something with 'i'
tmpCArray[i] = testStr[i];
}

// Via string.ToCharArray()
char[] cArray = testStr.ToCharArray();

// Copying the string into a char[]
char[] cArray1 = new char[testStr.Length];
testStr.CopyTo(cArray1, 0);

// With LINQ
char[] cArray2 = myString.Select(c => c).ToArray();
string testStr = "this is a string"

// Foreach loop
foreach (var c in testStr)
{
// Do something with 'c'
}

// For loop (should only be used when you NEED the index of the char, otherwise use foreach)
char[] tmpCArray = new char[testStr.Length];
for (int i = 0; i < testStr.Length; i++)
{
// Do something with 'i'
tmpCArray[i] = testStr[i];
}

// Via string.ToCharArray()
char[] cArray = testStr.ToCharArray();

// Copying the string into a char[]
char[] cArray1 = new char[testStr.Length];
testStr.CopyTo(cArray1, 0);

// With LINQ
char[] cArray2 = myString.Select(c => c).ToArray();
aCasualNon
aCasualNonOP9mo ago
ty
Want results from more Discord servers?
Add your server