-3

I am writing strings to an interface field that is defined as an array[256] and I'm not sure how to keep the junk at the end of the name from displaying.

Here's how I am setting it:

char[256] msg.name.Value = "This name".ToCharArray(); 

on the other side, I am unpacking the message into a database table:

newRow["Name"] = new string(msg.name.Value);

but I'm finding that the whole string is copied over with junk at the end. How do I get the junk parsed off the end of the "This name"? I'm used to having memcpy in C++ to do this.

Mrchief
  • 75,126
  • 20
  • 142
  • 189
Myca A.
  • 81
  • 7

1 Answers1

1

ToCharArray doesn't put a 0 at the end of it. So, I suppose, given the problem, you might try to implement an extension method that does something more like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string test = "This is a test";
            char[] testArr = test.ToPaddedCharArray(32);
            for (int i = 0; i < testArr.Length; i++)
            {
                Console.WriteLine("{0} = {1}", testArr[i], (int)testArr[i]);
            }
        }
    }

    public static class MyExtensions
    {
        public static char[] ToPaddedCharArray(this String str, int length)
        {
            char[] arr = new char[length];
            int minl = Math.Min(str.Length, length-1);
            for (int i = 0; i < minl; i++)
            {
                arr[i] = str[i];
            }
            for (int i = minl; i < length; i++)
            {
                arr[minl] = (char)0;
            }
            return arr;
        }
    }

}

This produces the output:

T = 84
h = 104
i = 105
s = 115
  = 32
i = 105
s = 115
  = 32
a = 97
  = 32
t = 116
e = 101
s = 115
t = 116
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
  = 0
Press any key to continue . . .
TJ Bandrowsky
  • 842
  • 8
  • 12