Recipe19.8.Converting a String to a char


Recipe 19.8. Converting a String to a char*

Problem

You have a string that you want to convert to a char*, which is essentially a pointer to the first element in a character array.

Solution

Use 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());         }     } } 

Discussion

To 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 Also

See Recipes 19.319.7; see the "Unsafe Code Tutorial" and the "Fixed Statement" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net