Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

Code Habit

MFC ) CString 본문

카테고리 없음

MFC ) CString

코드베어 2020. 1. 22. 19:20

MFC에서 문자열을 편하게 사용할 수 있도록 제공해주는 클래스로 문자 비교, 수정 등을 편하게 할 수 있다.

MFC뿐만 아니라 c 기반 프로젝트에서도 다음 헤더 파일을 추가하면 사용할 수 있다. <atlstr.h>

 

객체를 생성하면서 생성자 혹은 '=' 연산자를 통해 값 입력이 가능하다.

1
2
CString str(_T("test 문자열"));
CString str = _T("test 문자열"); 

 

+=, == 연산자를 활용하여 문자를 편하게 더하거나 비교가 가능하다.

1
2
3
4
5
6
7
8
9
CString str1 = _T("앞으로"); 
CString str2 = _T("코딩은"); 
CString str3 = _T("필요불가결한 요소이다."); 
CString str4 = str1 + _T("삶에서"+ str2 + str3; 
// str4 : "앞으로 삶에서 코딩은 필요 불가결한 요소이다." 
 
CString str = _T("철수"); 
if( str == _T("철수") ) { // true

 

 

다음 멤버함수를 통해 문자열의 길이를 쉽게 알 수 있다.

  • int GetLength() const
1
2
CString str = "coding"
int nCnt = str.GetLength(); // nCnt : 6

 

Format, AppendFormat을 이용하여 c스타일 등의 문자열을 편리하게 삽입할 수 있다. 

1
2
3
4
5
6
7
CString str = _T("");  
char sz[16= {0, }; 
 
strcpy( sz, "coding" ); 
str.Format(_T("재밌는 %s"), sz); 
str.AppendFormat(_T("이 유익하다.")); 
// str : 재밌는 coding이 유익하다. 

 

Find, Left, Right, Mid, Delete 함수를 이용하여 문자열을 손쉽게 수정할 수 있다. 

1
2
3
4
5
6
7
8
CString str = _T("coding_fun_life"); 
int nSel1 = str.Find('_'); // nSel1 : 6 
int nSel2 = str.ReverseFind('_'); // nSel2 : 10 
 
CString str2 = str.Left(nSel1); // str2 : coding 
CString str3 = str.Left(nSel2); // str3 : coding_fun 
CString str4 = str.Mid(73); // str4 : fun 
CString str5 = str.Mid(nSel2+1, str.GetLength()-nSel2-1); // str5 : life 

 

MakeUpper, MakeLower을 사용해 대문자 및 소문자 치환이 가능하다.

1
2
3
CString str = _T("CoDiNg"); 
CString str2 = str.MakeUpper(); // str2 : CODING 
CString str3 = str.MakeLower(); // str3 : coding