1. #1
    AceInfinity's Avatar
    Join Date
    Feb 2012
    Location
    Canada
    Posts
    1,716

    Using string's char* based constructor

    I'm fooling around in VS this morning after had no sleep:

    Code:
    private static unsafe string CToString(char[] charPtr, int startIndex)
    {
        fixed (char* c = &charPtr[startIndex]) return new string(c);
    }
    This takes the char array and an integer as parameters, and with that char array, converts it to a char* based on a start index specified by the second param, in order to take the address of a char[] which is considered an unfixed expression, you'll notice that I've put it into the fixed statement (this would be required otherwise you get a compiler error). From there we use the string constructor which requests a char* and return it.

    This returns the string value of each char afterwards from then on based on the specified startIndex.

    Note: If this char value is a value of 0, it will terminate itself at that point when returning the string. (I'll show an example to show you what I mean.)

    To test my function, here's a test snippet inside of a button click:
    Code:
    private void button1_Click(object sender, EventArgs e)
    {
    	char[] vals = new char[] { 'h', 'e', 'l', 'l', 'o' };
    	string s = CToString(vals, 0);
    	Console.WriteLine(s);
    }
    If you did this:
    Code:
    private void button1_Click(object sender, EventArgs e)
    {
    	char[] vals = new char[] { 'h', 'e', 'l', 'l', 'o', (char)0, 't', 'e', 's', 't' };
    	string s = CToString(vals, 0);
    	Console.WriteLine(s);
    }
    You would notice that none of the values after '(char)0' would show...

    Notes:
    -Must compile with unsafe context on
    -Must declare unsafe code in the method header or in it's own little statement/wrapper.
    Last edited by AceInfinity; 06-19-2012 at 12:13 AM.
    \n\n

    Automation Programmer
    Development Site: aceinfinity.net


    • Ad Bot

      advertising
      Beep.

        
       

Similar Threads

  1. [C#] Console Based Game - TicTacToe
    By AceInfinity in forum Programming
    Replies: 5
    Last Post: 03-30-2013, 11:42 AM
  2. [C#] Fooling around with bitwise string encoding
    By AceInfinity in forum Programming
    Replies: 0
    Last Post: 01-18-2013, 12:58 PM
  3. DriverTable - Scan Driver String with Javascript Bookmarklet
    By AceInfinity in forum BSOD, Crashes, Kernel Debugging
    Replies: 11
    Last Post: 12-17-2012, 04:53 AM
  4. IE10 User Agent String Update
    By JMH in forum Web Browser News
    Replies: 0
    Last Post: 07-14-2012, 04:27 PM
  5. Replies: 0
    Last Post: 07-07-2012, 08:14 PM

Log in

Log in