字符串
C语言中的字符串
基本概念
字符串常量
如: const char* message = “hello”; 此为定义一个字符串常量,并且最后包含一个终止符 \0; (此处需要const的原因,"hello"的类型实际是 const char[6],如何不适用const ,就意味 可以通过message[i] 进行修改)
无法使用sizeof来计算字符串长度,因为使用sizeof计算的结果是指针的值,
需要是使用strlen来计算,它返回的值不包含 \0的大小
字符数组
用来存放字符的数组,如:char strArr[] = {‘h’, ‘e’, ‘l’, ‘l’ , ‘o’}; // sizeof is 5, strlen 返回错误因为没有\0
或者 char strArr[] = “hello”; // sizeof is 6
对于字符串char类型,标准库提供了一些常用的函数:
strcmp(char const* s1, char const s2) // 0 is equal
strchr(char const str, int ch) // find ch in str and return null if not found
strstr(char cosnt* str, char const* substr);// return str + 2’s address
C++中string类
可以使用char* 直接初始化string,string 没有\0的概念,通过size获取字符串数目
char* str = “hello”;
std::string str1(str, 3); // str1 is “hel”;
对于 += 操作,支持 string 对象,“str” , ‘a’;
对于 append 支持 append(string);
对于pushbach 支持 pushback(‘c’);
比较2个string,可以直接使用 ==,同时也提供类似 c风格的 compare函数
使用substr来获取子串,示例:获取文件的后缀:
std::string sstr("filename.txt.");
size_t lastDotPos = sstr.rfind('.');
std::string suffix;
if (lastDotPos >= 0 && lastDotPos < sstr.size() - 1)
{
suffix = sstr.substr(lastDotPos + 1);
}
string.find 查找字符串:如果找不到返回string::npos,找到返回索引
string.erase(); 同QString的remove
string 与 wstring之间的转换
#include <locale>
#include <codecvt>
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring w_str = converter.from_bytes(str);
std::string str = converer.to_bytes(w_str);
std::wstring wide(L"你好h"); // wide.size() is 3 ok
std::string narrow("世界h"); // narrow.size() is 5,中文2个字节
注意:包含中文的string 如果转换成wstring 会崩溃
使用一下方式进行替换:
#include <windows.h>
std::wstring string2wstring(const std::string& str)
{
std::wstring result;
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
TCHAR* buffer = new TCHAR[len + 1];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
buffer[len] = '\0';
result.append(buffer);
delete[] buffer;
return result;
}
std::string wstring2string(const wstring& wstr)
{
std::string result;
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
char* buffer = new char[len + 1];
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
buffer[len] = '\0';
result.append(buffer);
delete[] buffer;
return result;
}
char* -> wchar_t *
typedef WCHAR TCHAR, *PTCHAR;
// const char* tmp = test_info->name()
TCHAR temp_path_[MAX_PATH];
TCHAR temp_path[MAX_PATH] = { '\0' };
TCHAR test_name_wide[MAX_PATH] = { '\0' };
// We want the temporary directory to be what the OS returns
// to us, + the test case name.
GetTempPath(MAX_PATH, temp_path);
// The test case name is exposed to use as a c-style string,
// But we might be working in UNICODE here on Windows.
int dwRet = MultiByteToWideChar(CP_ACP, 0, test_info->name(),
static_cast<int>(strlen(test_info->name())),
test_name_wide,
MAX_PATH);
if (!dwRet) {
assert(false);
}
StringCchPrintfW(temp_path_, MAX_PATH, L"%s%s", temp_path, test_name_wide);
CreateDirectory(temp_path_, NULL);