字符指针与字符串变量的转换
VC.NET中的String類是利用Unicode字符集編碼來表示文本。Unicode字符集中每個字符(漢字、英文字母)都占2個字節,且其字符串是以2個連續的/0結尾的。
ANSI的ASCII字符集是最常見的字符集,常用于表示txt的文本文件。在ASCII字符集中英文占一個字節,漢字2個字節,且其字符串是以一個/0結尾的。
在利用VC.NET進行混合編程時,經常需要實現String與char*的互轉,例如在TextBox控件中輸入的Text作為fopen或者CreateFile的文件名參數時,常需要實現char*的轉化。故提供如下的轉化方法:
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
int main(array<System::String ^> ^args)
{
?// String^ converts to char*
?char szDestOutChar[256];
?String^ SrcInStr = "C://Documents and Settings//Adiminstrator//我的文檔//swq.txt ";
?int SourceStrLen = SrcInStr->Length;
?wchar_t *pwszStr = new wchar_t[SourceStrLen + 1];
?array <System::Char>^ pClr = SrcInStr->ToCharArray();
?for (int i = 0; i < SourceStrLen; i++)
?{
?? pwszStr[i] = pClr[i];
?}
ourceStrLen] = '/0';
?::WideCharToMultiByte(CP_ACP, NULL, pwszStr, -1, szDestOutChar, 256, NULL, NULL);
?// char* converts to String^
?char* szInSrcChar =? "C://Documents and Settings//Adiminstrator//我的文檔//swq.txt";
?int wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, szInSrcChar, strlen(szInSrcChar), NULL, 0);
?wchar_t* wszStr = new wchar_t[wcsLen + 1];
?::MultiByteToWideChar(CP_ACP, NULL, szInSrcChar, strlen(szInSrcChar), wszStr, wcsLen);
?wszStr[wcsLen] = '/0';
?String^ ClrOutStr = gcnew String(wszStr);
?System::Console::WriteLine("Press ENTER key to exit !");
?System::Console::Read();
?delete pwszStr
delete wszStr;
?return 0;
}
詳細出處參考:http://www.itqun.net/content-detail/75523_3.html
詳細出處參考:http://www.itqun.net/content-detail/75523_2.html
詳細出處參考:l
總結
以上是生活随笔為你收集整理的字符指针与字符串变量的转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序中带参数返回上一页的方法总结(
- 下一篇: Crontab定时任务访问url实例