如何解析char中的垃圾[256]

时间:2014-09-05 21:00:16

标签: c# arrays string

我正在将字符串写入一个定义为数组[256]的接口字段,我不知道如何防止名称末尾的垃圾显示。

以下是我如何设置它:

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

另一方面,我正在将消息解压缩到数据库表中:

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

但我发现整个字符串最后都被垃圾复制了。如何从“此名称”的末尾解析垃圾?我习惯在C ++中使用memcpy来执行此操作。

1 个答案:

答案 0 :(得分:1)

ToCharArray并没有在它的末尾添加0。所以,我想,考虑到这个问题,你可能会尝试实现一个更像这样的扩展方法:

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;
        }
    }

}

这会产生输出:

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 . . .