Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String[0] vs ToCharArray then Char[0]

Tags:

c#

.net

char

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];
like image 317
mildse7en Avatar asked Oct 28 '25 01:10

mildse7en


2 Answers

  • If you need a char at particular index, use "cats"[2]
  • If you need the whole string as char array, use "cats".ToCharArray()
like image 65
abatishchev Avatar answered Oct 29 '25 16:10

abatishchev


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);
like image 40
Robert Rouhani Avatar answered Oct 29 '25 17:10

Robert Rouhani