我无法在 VC++ 2010 中将 String 转换为 char 数组

I cannot convert String into char array in VC++ 2010

我正在尝试 VC++ 中的凯撒密码程序。 我尝试将 String 转换为 char 数组..但是当我显示它时它显示 true..

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e){        
    System::String^ plain=(textBox1->Text);
    int i,j;
    char* msg = (char*)Marshal::StringToHGlobalAnsi(plain).ToPointer();     
    int length=strlen(msg);

    for(i=0;i<length;i++)
    {
        if(isalpha(msg[i]))
        {
            msg[i]=tolower(msg[i]);
            for(j=0;j<3;j++)
            {
                if(msg[i]=='z')
                {
                    msg[i]='a';
                }
                else
                {
                    msg[i]++;
                }
            }
        }
     }    

    label3->Text=System::Convert::ToString(msg);
}

我明白了。 一行的改变创造了奇迹

更改此行

label3->Text=System::Convert::ToString(msg);

label3->Text=gcnew String(msg,0,100);

这是一个简单的实现:

static String^ CaesarCipher(String^ input, int shift)
{
    const int numLetters = 'z' - 'a' + 1;
    shift = shift % numLetters;

    auto sb = gcnew System::Text::StringBuilder(input->Length);

    for each (auto c in input)
    {
        if (c >= 'a' && c <= 'z')
        {
            c += shift;

            if (c > 'z')
                c -= numLetters;
            else if (c < 'a')
                c += numLetters;
        }
        else if (c >= 'A' && c <= 'Z')
        {
            c += shift;

            if (c > 'Z')
                c -= numLetters;
            else if (c < 'A')
                c += numLetters;
        }

        sb->Append(c);
    }

    return sb->ToString();
}

看到了吗?根本不需要编组,因为您没有调用本机代码。

您的原始代码正在泄漏内存,因为您调用了 Marshal::StringToHGlobalAnsi 而没有调用 Marshal::FreeHGlobal:

StringToHGlobalAnsi is useful for custom marshaling or when mixing managed and unmanaged code. Because this method allocates the unmanaged memory required for a string, always free the memory by calling FreeHGlobal. StringToHGlobalAnsi provides the opposite functionality of Marshal.PtrToStringAnsi.

这在您的脑海中应该是自动的:当您分配非托管内存时,您负责释放它。