天天看點

MFC統計字元串長度和字元數

作者:黑貓程式設計

界面繪制

軟體版本:Microsoft Visual Studio Community 2022 (64 位)

MFC統計字元串長度和字元數

編輯框ID:IDC_EDIT_STRING_INPUT

統計按鈕ID:IDC_BTN_CALC

靜态文本框ID:IDC_STATIC_SHOW_RESULT

設定支援多行輸入和回車輸出:

MFC統計字元串長度和字元數

編輯框回車退出問題

重寫PreTranslateMessage方法:

MFC統計字元串長度和字元數
BOOL CDemo1App::PreTranslateMessage(MSG* pMsg)
{
	if (pMsg->message == WM_KEYDOWN) {
		switch (pMsg->wParam) {
		case VK_RETURN:
			break;
		}
	}

	return CWinApp::PreTranslateMessage(pMsg);
}           

按鈕按下事件

void CDemo1Dlg::OnBnClickedBtnCalc()
{
	CString string_input;
	GetDlgItemText(IDC_EDIT_STRING_INPUT, string_input);
	//OutputDebugString(string_input);
	int len = string_input.GetLength();
	int cnt = 0;

	for (int i = 0; i < len; i++) {
		if ((BYTE)string_input[i] > 0x7f) i++;
		cnt++;
	}

	CString string_output;
	string_output.Format(_T("字元串長度:%d,字元個數:%d"), len, cnt);
	SetDlgItemText(IDC_STATIC_SHOW_RESULT, string_output);
}           

Unicode字元集下:字元串長度等于字元個數

MFC統計字元串長度和字元數

多位元組字元集下:一個字占兩個位元組

ANSI字元集通常使用0x00~0x7f 範圍的1個位元組來表示1個英文字元,超出的部分使用 0x80-0xFFFF來編碼的。
MFC統計字元串長度和字元數