C++ 的字符串和操作
1. 标准 C++ 的字符串数据类型是 string 类. (需要包含头文件<string> 或 <string.h>)
申明:
string myStr;
操作:
//初始化: string myStr="Hello World!"; //赋值: myStr="Ni Hao"; //转化: char* -> string char a[]="Hello World!"; string b; b=a; //转化: string -> char* string b="Ni Hao"; char a[]="Hello World!"; strcpy(a,b.c_str()); //string 对象不能自动转化为c字符串。需要利用成员函数c_str(); //转化: 字符串->数字 int atoi(const char *nptr); double atof(const char *nptr); long atol(const char *nptr);
字符串函数:
串长度: int strlen(char *str)
串拷贝: char *strcpy(char *targetStr,char *orignalStr);
串连接: char *strcat(char *str1,char *str2)
串比较: int strcmp(char *str1,char *str2) //比较的是字符的ASCII码, str1>str2 返回1, 相等为0
串定位: char *strchr(char *str,char ch) //找到返回字符在字符串中的位置,否则返回-1;
2. CString 类 是Visual C++中最常用的字符串类,继承自CSimpleStringT类,主要应用在MFC和ATL编程中
声明:
CString str;
在操作字符串 CString类之前,先了解Windows字符的类型.
┌──────────────────────────────┐
类型 MBCS 中含义 Unicode 中含义
TCHAR char wchar_t
WCHAR wchar_t wchar_t
LPSTR char* char*
LPCSTR const char* const char*
LPWSTR wchar_t* wchar_t*
LPCWSTR const wchar_t* const wchar_t*
LPTSTR TCHAR* TCHAR*
LPCTSTR const TCHAR* const TCHAR*
char 标准c的字符类型(1Byte)
wchar_t 保存UNICODE字符集的类型(2Byte)
└──────────────────────────────┘
TCHAR的定义如下:
#ifdef UNICODE typedef wchar_t TCHAR; #else typedef char TCHAR; #endif
再了解一个宏_T(),使用宏_T(),使代码有了unicode的意识。
#ifdef UNICODE #define _T(x) L##x #else #define _T(x) x #endif
##是一个预处理操作符,它可以把两个参数连在一起.
TCHAR str[] = _T("I love c++.");
操作:
//初始化.
//法1)直接初始化:
CString str="Hello World!";
//法2)通过构造函数初始化化:
CString str("aaaaaaaaaa");
CString str('a',10); //长度为10的“aaaaaaaaaa"字符串.
//法3)通过加载字符串资源:
CString str;
str.LoadString(IDS_STR);
//法4)使用CString类的成员函数Format进行初始化:
CString str;
int total=100;
str.Format(_T("The total is %d"), total);
//转化: char* -> CString
char *p1="This is a string in 8-bit only.";
TCHAR *p2=_T("This is a string with unicode-aware.");
LPTSTR p=_T("This is a string with unicode-aware."); //等价于上句.
CString s1=p1;
CString s2(p2);
CString s3(p3);
//转化: CString -> char*
//法1)使用LPCTSTR 操作符.
CString s("Hello World!");
LPCTSTR p=s; //LPCTSTR 操作符(或者更明确地说就是const TCHAR * 操作符)在 CString 类中被重载了,该操作符的定义是返回缓冲区的地址(指向 CString 的 字符串指针).
//法2)使用 CString 对象的 GetBuffer 方法
CString s(_T("Hello World!");
LPTSTR p=s.GetBuffer();
//s.ReleaseBuffer();
//delete p;
//法3)使用控件
CString str;
CListBox *pLB = (CListBox*)GetDlgItem(YOUR_LISTBOX_ID); // 获取你的ListBox对象指针,
//YOUR_LISTBOX_ID为其资源标识
pLB->GetText(pLB->GetCurSel(), str); // 获取当前选项字符串并存储于str中
浙公网安备 33010602011771号