将字符数组转换为 System::String^

Converting char-array to System::String^

作为我的代码的一部分,我需要在文本框中输出一个已加密的 8 个字符的字符串。所以我需要将 8 个字符的数组转换为 System String^。我尝试了以下方法:

char result[8];
for(int i=0; i<8; i++)
{
    result[i] = (char)DecimalCypher[7-i];
}

textBox3->Text = gcnew String(result);

但是,文本框显示的字符超过 8 个。 8 个字符会根据输入而变化,其余的将保持原样。 例子, 如果我的输入是

andrew12

,文本框中的输出为

T)W+"ZizBVÎ pé

但是如果我的输入是

andrew33 , the output will be : A1-1`+TaBVÎ pé

最后 6 个字符相同..但一开始就不应该出现在这里。 重要的是前 8 个字符!

知道为什么会这样吗?

在填充 char 数组以将其用作字符串时,请始终确保最后一个有效字节之后的字节为空。更多信息:What is a 'Null Terminated String' ?

char result[8];

创建变量result并为8个字符分配space。

for(int i=0; i<8; i++)
{
    result[i] = (char)DecimalCypher[7-i];
}

填满result中的所有8个字符。

textBox3->Text = gcnew String(result);

创建一个新的字符串 result 就好像 result 是一个 c 风格的字符串。不幸的是 result 不是 c 风格的字符串,因为它没有被 null 终止。

改为使用:

char result[9];

创建变量result并为9个字符分配space。

result[8] = '[=14=]';

null 终止 result.

for(int i=0; i<8; i++)
{
    result[i] = (char)DecimalCypher[7-i];
}

result中填满8个字符。第 9 个被 null 使用。

textBox3->Text = gcnew String(result);

用 c 风格的字符串创建一个新字符串 result