筆記:字符串函數(CString)

int GetLength()//字符串長度
int Compare(PCXSTR psz)//比較
bool IsEmpty()//是否爲空
PXSTR GetBuffer()//返回字符指針
void Format(PCXSTR pszFormat)//格式化字符串

int Find(XCHAR ch, int iStart = 0) const//查找字符
int Find(PCXSTR pszSub, int iStart = 0) const//查找字符串
int Insert(int iIndex, XCHAR ch)//插入字符
int Insert(int iIndex, PCXSTR psz)//插入字符串
int Delete(int iIndex, int nCount = 1)//刪除指定位置的字符
int Remove(XCHAR chRemove)//移除字符
int Replace(XCHAR chOld, XCHAR chNew)//替換字符
int Replace(PCXSTR pszOld, PCXSTR pszNew)//替換字符串
void Empty()//清空字符串
CStringT& MakeUpper()//轉換爲大寫
CStringT& Trim()//去除左右兩側空格

CStringT Left(int nCount) const//截取字符串左邊的數據
CStringT Mid(int iFirst) const//截取字符串中間的數據
CStringT Mid(int iFirst, int nCount) const//截取字符串中間nCount個數據
CStringT Right(int nCount) const//截取字符串右邊的數據


#include <afx.h>	//#include <atlstr.h>
//#include <afxwin.h>//AfxMessageBox()
#include <iostream>

void test()
{
	CString s1 = _T("abc123");
	CString s2 = _T("abc123");
	CString s3 = _T("ABC123");
	CString s4 = _T("abc中英");
	CString s5 = _T("");
	CString s6;
	CString s7;
	s7.Format(L"%s%d", L"date:", 2020);

	if (s1 == s2)
		std::cout << "s1、s2相等" << std::endl;
	if (s1.Compare(s2) == 0)
		std::cout << "s1 s2 equal" << std::endl;
	if (s1.CompareNoCase(s3) == 0)
		std::cout << "s1 s3 equal" << std::endl;
	int len = s4.GetLength();//Unicode下 5
	std::cout << len << std::endl;
	if (s5.IsEmpty())
		std::cout << "s5 is empty" << std::endl;
	if (s6.IsEmpty())
		std::cout << "s6 is empty" << std::endl;
	std::cout << (CStringA)(s7.GetBuffer()) << std::endl;
}

void test2()
{
	CString s(_T("abcdef"));
	int index = s.Find(L"bc");//成功返回位置,否則返回-1
	std::cout << index << std::endl;
	
	CString sub1 = s.Left(4);
	std::cout << (CStringA)sub1 << std::endl;

	CString sub2 = s.Mid(2, 3);
	std::cout << (CStringA)sub2 << std::endl;

	
}

void test3()
{
	CString s = _T("  abc 123 w97  ");
	s.MakeUpper();
	std::cout << (CStringA)s << std::endl;
	s.Trim();//去除左右兩邊空格
	std::cout << "-" << (CStringA)s << "-" << std::endl;
	s.Replace(L" ", L"");//去除全部空格
	std::cout << (CStringA)s << std::endl;
	s.Delete(0);//刪除第0個字符
	std::cout << (CStringA)s << std::endl;
	s.Insert(1, L"zw");//在第1個字符後插入
	std::cout << (CStringA)s << std::endl;
	s.Empty();
	std::cout << s.IsEmpty() << std::endl;
}

int main()
{
	test();
	test2();
	test3();
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章