Say I want to get the third letter in a string.
string s = "cats";
what is the difference between using s[2] to get the value, as I see most examples online use:
char[] c = s.ToCharArray();
char x = c[2];
"cats"[2]"cats".ToCharArray()The s[2] method simply looks up the character in that position and returns it.
The s.ToCharArray(); method allocates a new char[], then c[2] looks it up in the array.
If you need just a single character, use the s[2] method as the ToCharArray() method is wasteful. If you need all the characters in the string as a char[] then the ToCharArray() method is cleaner and probably faster (I haven't done any benchmarking, so don't hold me to that).
EDIT:
Both MS.NET and Mono's implementations of string.ToCharArray() use unsafe code that pins the internal char and a duplicate char[] and operates on the pointers. This is definitely faster than calling the indexer for every character and is probably faster than using an enumerator to iterate over all the characters. Plus I find it a lot cleaner, especially in the case where it's used as a parameter:
DoSomethingWithCharArray(s.ToCharArray());
vs
int i = 0;
char[] arr = new char[s.Length];
foreach (char c in s)
{
arr[i] = c;
i++;
}
DoSomethingWithCharArray(arr);
or
char[] arr = new char[s.Length];
for (int i = 0; i < s.Length; i++)
{
arr[i] = s[i];
}
DoSeomthingWithCharArray(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With