string 与 char* lpstr 的一些混合操作

 

Use a C++ std::string in your program, it'll save you a lot of grief with memory management, string lengths, and even
provides a lot of basic (and advanced) operations, with relatively simple syntax ( = for assignment, + for concatenation,
 size() for string size ... )

Pass the internal (const) char*-string to API functions when needed by calling std::string::c_str()
Copy the internal char*-string to a char array with std::string::copy() when you must. Remember to add the NULL, 
char*-strings suck.

Usage :


#include <string>
using namespace std; // to remove the std:: prefix

// a pointer to a char*-string (or an array of char*-string)
LPSTR* lpPathList;

// assign the first char*-string from lpPathList
string str1 = lpPathList[0]; 

// copy the C++ string to another C++ string, it's easy
string str2 = str1;

// pass the underlying const char*-string to a C API function
// The API function cannot modify the string.
myApiFunction1( str1.c_str() );

// copy the string into a char*-string buffer, 
// so that a C API can modify it
char buffer[256];
int size = str1.copy( buffer, 255 );
buffer[size] = 0; // Add the NULL terminator
myApiFunction2( buffer );
// now put back the modified buffer into the C++ string
str1 = buffer;
// or, if you want to get all the strings from you char*-string array      
const int count = 10; // Assume you had 10 char*-strings

int i;
string str;
for( i = 0; i < count; ++i )
{
   str += lpPathList[i]; // Append the char*-string.
   str += "/n";          // Append a newline to separate them.
}

// Create a big enough buffer, '+1' for the NULL termination
char* buffer = new char[str.size() + 1];

// Copy the combined strings to the buffer
int size = str.copy( buffer, str.size() );
buffer[size] = 0; // Add the NULL terminator

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值