2014-09-05 48 views
-3

我正在寫字符串的接口字段被定義爲數組[256],我不知道如何保持名稱末尾的垃圾顯示。如何解析字符的垃圾[256]

下面是我如何設置它:

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

在另一邊,我拆包消息到數據庫表:

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

,但我發現,整個字符串最後複製垃圾。我如何從「這個名字」的末尾解析垃圾?我習慣於在C++中使用memcpy來做到這一點。

+2

,你看到的是什麼垃圾? – Mrchief 2014-09-05 21:01:33

+0

http://stackoverflow.com/questions/2996487/memcpy-function-in-c-sharp – MethodMan 2014-09-05 21:02:39

+0

這是否工作? 'char [256] msg.name.Value =「This name \ 0」.ToCharArray();' – Dan 2014-09-05 21:04:59

回答

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