Recipe 19.8. Converting a String to a char*ProblemYou have a string that you want to convert to a char*, which is essentially a pointer to the first element in a character array. SolutionUse the ToCharArray method of the string type to create a char* character array: public static void ConvertStringToCharPtr(string str) { unsafe { fixed (char* pStr = str.ToCharArray()) { // Display some of the characters. Console.WriteLine(pStr->ToString()); // Could also have been // written as pStr[0].ToString(). Console.WriteLine(pStr[1].ToString()); Console.WriteLine(pStr[2].ToString()); Console.WriteLine(pStr[3].ToString()); } } } DiscussionTo get a character array from a string object, you can use the overloaded ToCharArray method on the string object. This method is overloaded to accept no arguments and convert the entire string to a character array or to take two integer arguments and convert only a substring of the entire string to a character array. These two integer parameters hold a startIndex value and a length value. The substring starting at the startIndex position in the string and ending at the (startIndex + length) position in the string is converted to a character array. See AlsoSee Recipes 19.319.7; see the "Unsafe Code Tutorial" and the "Fixed Statement" topics in the MSDN documentation. |