在我的新工作中,我们不使用MFC,但幸运的是我们使用标准库和C++11。因此,我遇到了与c00000fd相同的问题。感谢BitTickler的回答,我想到了通过&s[0]
或&s.front()
来使用字符串的内部缓冲区进行Win32-API。
使用一个收缩内部字符串缓冲区的 Win32-API 函数
假设你有一个字符串,希望通过Win32-API函数(例如::PathRemoveFileSpec(path)
)将其缩短,可以采用以下方法:
std::string path( R("?(C:\TESTING\toBeCutOff)?") );
::PathRemoveFileSpec( &path.front() );
path.resize( strlen( path.data() ) );
path.shrink_to_fit();
Unicode版本:
std::wstring path( LR("?(C:\TESTING\toBeCutOff)?") );
::PathRemoveFileSpec( &path.front() ); // Using the Win32-API
// and the the string's internal buffer
path.resize( wcslen( path.data() ) ); // adjust the string's length
// to the first \0 character
path.shrink_to_fit(); // optional to adjust the string's
// capacity - useful if you
// do not plan to modify the string again
使用扩展内部字符串缓冲区的Win32-API函数
假设您有一个字符串需要在Win32-API函数中进行扩展或填充 - 例如使用::GetModuleFileName(NULL, path, cPath)
函数来检索可执行文件的路径 - 您可以按照以下方式操作:
std::string path;
path.resize(MAX_PATH);
::GetModuleFileName( NULL, &path.front(), static_cast<DWORD>( path.size() ) );
path.resize( strlen( path.data() ) );
path.shrink_to_fit();
Unicode版本:
std::wstring path;
path.resize(MAX_PATH); // adjust the internal buffer's size
// to the expected (max) size of the
// output-buffer of the Win32-API function
::GetModuleFileName( NULL, &path.front(), static_cast<DWORD>( path.size() ) );
// Using the Win32-API
// and the the string's internal buffer
path.resize( wcslen( path.data() ) ); // adjust the string's length
// to the first \0 character
path.shrink_to_fit(); // optional to adjust the string's
// capacity - useful if you
// do not plan to modify the string again
当您最终缩小字符串时,与MFC替代方案相比,仅需要在扩展字符串的内部缓冲区时再添加一行代码;而在缩小字符串时,几乎有相同的开销。
std::string
方法相对于
CString
方法的优势在于,您无需声明额外的C-String指针变量,只需使用官方的
std::string
方法和一个
strlen
/
wcslen
函数即可。
上面的方法仅适用于缩小变体并且所得到的 Win32-API 缓冲区是以空字符结尾的情况。但对于返回未终止字符串的非常特殊的情况,则必须 - 类似于
CString :: ReleaseBuffer
方法 - 显式知道并指定新字符串 / 缓冲区长度,即
path.resize(newLength)
- 就像
CString
替代方案中的
path.ReleaseBuffer(newLength)
一样。
CharLower
API不是CharLower
,而是一些将修改其输入缓冲区但我需要从std::string
中获取的任意API。我该怎么做?这就是我的问题。 - c00000fdstd::string
对象所需的代码都已经存在,无论是在std::string
类本身中还是通过使用标准库中的其他函数。你不必从头开始重写或启动任何东西,因为代码已经存在供你使用。大小写转换、修改子字符串、追加、前置、插入,所有这些功能都已经存在。 - Some programmer dude