VC++中取得字符串长度
VC++ 里“取字符串长度”的各种写法,这里按常见类型给出最稳妥的方式,并区分“字符数”和“字节数”(做 CRC 时尤其重要)。
- C++ 标准字符串
std::string(常用于 UTF‑8 或 ANSI,元素是 char)
字符数(也是字节数):
std::string s = "...";
size_t nChars = s.size(); // == s.length()
size_t nBytes = s.size(); // std::string 中 1 字符 = 1 字节
注意:std::string 可能包含嵌入的 '\0',size() 会统计,strlen() 不会。
std::wstring(Windows 下 wchar_t=2 字节,UTF‑16 code unit)
字符数(以 wchar_t 为单位)与字节数:
std::wstring ws = L"...";
size_t nWchars = ws.size(); // wchar_t 个数
size_t nBytes = ws.size() * sizeof(wchar_t); // 字节数(MSVC 下乘以 2)
其他定宽字符串
std::u16string:字符数 = u.size();字节数 = u.size() * 2
std::u32string:字符数 = u.size();字节数 = u.size() * 4
提示:
.size()/.length() 返回 size_t;在 x64 为 8 字节,若要转 int 请判断范围后再窄化。
UTF‑8 的“字符数”(人类感知的字形)≠ 字节数,需要解码或用 ICU 等库统计。
MFC/ATL 字符串
CStringA(窄字节,1 字符 = 1 字节)
字符数/字节数:
CStringA sa = "...";
int nChars = sa.GetLength();
int nBytes = sa.GetLength();
CStringW(宽字符,wchar_t)
字符数与字节数:
CStringW sw = L"...";
int nWchars = sw.GetLength();
int nBytes = sw.GetLength() * sizeof(wchar_t); // 通常 *2
CString(TCHAR 版,随 UNICODE 切换)
字符数与字节数:
CString s = _T("...");
int nTchars = s.GetLength();
int nBytes = s.GetLength() * sizeof(TCHAR); // ANSI=1,UNICODE=2
说明:
CString 的 GetLength() 返回字符数,不含末尾的 '\0'。
计算字节数时请乘以对应元素大小。
C 风格指针(WinAPI 常见)
LPCSTR(窄字节):
LPCSTR p = "...";
size_t nChars = strlen(p); // 不统计嵌入 '\0'
size_t nBytes = nChars; // char 即 1 字节
LPCWSTR(宽字节):
LPCWSTR p = L"...";
size_t nWchars = wcslen(p);
size_t nBytes = nWchars * sizeof(wchar_t);
LPCTSTR(随 UNICODE):
LPCTSTR p = _T("...");size_t nTchars = _tcslen(p);size_t nBytes = nTchars * sizeof(TCHAR);
安全变体(可限制最大扫描长度,避免越界):strnlen、wcsnlen、_tcsnlen;MSVC 也有 *_s 系列。
与 CRC/二进制长度相关的要点
二进制输入请用容器的 size()(字节数)而不要用 strlen()(会在首个 '\0' 处停止)。
宽字符串作为字节缓冲计算 CRC 时:字节数 = 字符数 × sizeof(wchar_t)。
示例(与你之前的 CRC 场景对齐):
uint32_t StringCrc(const std::string& s) {
return s.empty() ? 0u
: CheckCrc::Crc32(reinterpret_cast<const uint8_t*>(s.data()),
static_cast<int>(s.size()));
}
uint32_t StringCrc(const std::wstring& ws) {
return ws.empty() ? 0u
: CheckCrc::Crc32(reinterpret_cast<const uint8_t*>(ws.data()),
static_cast<int>(ws.size() * sizeof(wchar_t)));
}
|