반응형

http://ncanis.tistory.com/334


이외 도움될만한 정보 : http://darkstings.blog.me/30080591302
 

문자열 string

#include "StdAfx.h"
#include "StringTest.h"
#include <algorithm> //transform 사용
#include <functional> //bind1st

using std::string; // 이렇게 지정해준다.


StringTest::StringTest()
{
log("StringTest 생성자 호출");
}

StringTest::~StringTest(void)
{
log("StringTest 소멸자 호출");
}

void StringTest::test()
{
log("============ string class ==========");
// 생성자

std::string s0; // 비어있는 string
std::string s1("012345",3); // 결과: 012
std::string s2("abcdefg",0,1); // 결과:a


log("비어 있는 String=%s, length=%d, isEmpty=%d",s0.c_str(),s0.length(), s0.empty()); // C-String 형으로 리턴, 문자열 + \0
log("문자열로 초기화=%s",s1.data()); // 문자열 내용 반환
log("문자열의 index~index 안 데이터로 생성=%s",s2.c_str());
// 문자열 기본정보

s1.reserve(100); // 메모리 공간 미리 할당
log("가질수있는 문자 최대 갯수=%d",s1.max_size());
log("메모리 재할당 없이 가질수 있는 최대 문자수 =%d",s1.capacity());

// 문자 추가

s1 = "0123456";
s2 = "abcdefg";
s1.append(s2,0,s2.npos); // 결과: 0123456abcdefg , s2의 0~s2.npos 위치의 문자열을 맨뒤에 추가
s1.insert(0,"add"); // 결과: add0123456abcdefg. 문자열을 0번째에 끼어넣기
log("append=%s",s1.c_str()); 


// 문자 복사 copy ( s1 -> s4 로 복사) char* s, size_t n, size_t pos = 0

char s4[100];
int length = s1.copy(s4,s1.length(), 0);
s4[length] = '\0';
log("copy=%s",s4); // 결과: 1234567



// 문자열 원소 접근

s1 ="0123456";
log("0번째 문자 = %c, %c",s1.at(0), s1[1]); // 결과:0,1 =>문자 접근 (오버시 exception 발생)


// 문자 제거

s1 = "0123456";
s1.erase(1); // 결과:0
log("2번째 문자부터 제거=%s",s1.data()); // 문자 접근 (오버시 exception 발생)
s1.empty();


// 문자열 할당 (문자열, 포지션, 갯수)

s1 = "0123456";
s1.assign("abcdef",0,3); // 결과: abc, 0번째 부터 3개문자를 할당
log("assign 문자열 할당 = %s",s1.data()); 


// 문자열 교체

s1 = "abcdef";
s2="0123456";
s1.replace(0,1,"5555"); // 결과: 5555bcdef
s1.swap(s2); // 결과: s1=0123456, s2 = 5555bcdef
log("문자열 교체 s1=%s, s2=%s",s1.data(),s2.data()); 


// substring

s1 = "0123456";
s1 = s1.substr(0,3); // 결과: 012, 0번째부터 3개문자를 짤라 할당한다.
log("substr s1=%s",s1.data()); 


// search

s1 = "01234560123456";
int index = s1.find("2",0);  // 결과 :2, 0번째 위치부터 검색해서 2의 위치를 찾는다.
int index2 = s1.rfind("2");  // 결과 :9, 끝에서 부터 검색해서 2의 위치를 찾는다.
int index3 = s1.find_first_of("13"); // 결과 : 1, 1 or 3이 있는 첫번째 위치를 찾는다.
int index4 = s1.find_last_of("13"); // 결과 :  10, 1 or 3이 있는 마지막 위치를 찾는다.

int index5 = s1.find_first_not_of("0"); // 결과 : 1, 0이 아닌 문자가 나오는 첫번째 위치
int index6 = s1.find_last_not_of("6"); // 결과 : 5, 0이 아닌 문자가 나오는 마지막 위치

// 검색 실패시 std::string::npos 를 리턴한다. std::string::size_type 형이다.
log("search find=%d, rfind=%d, find_first_of=%d, find_last_of=%d, find_first_not_of=%d,find_first_not_of=%d",index,index2,index3, index4,index5, index6); 


// 반복자
ConvertCase();
}

// 반복자 이용
void StringTest::ConvertCase(){
//기본 (영어만 가능)
char str[] = "abcdefg";
strupr(str); // strlwr
log("대소문자 변환=%s",str);

// custom 사용
//std::string msg0("abcdefg");
//std::transform(msg0.begin(), msg0.end(), msg0.begin(), toUpper);

// string 반복자 이용 (영어만 가능)
std::string msg("abcdefg");
std::transform(msg.begin(), msg.end(), msg.begin(), toupper);
log("대소문자 변환=%s",msg.data());

//locale 이용 (모든 나라 가능)
char* org_lc = setlocale(LC_CTYPE, NULL); //현재 locale 저장
setlocale(LC_CTYPE, "spanish");
std::wstring str2(L"pequeño");
std::transform( str2.begin(), str2.end(), str2.begin(), towupper); 
setlocale(LC_CTYPE, org_lc);
log("locale 이용 대소문자 변환=%s",str2.data());

//facet 이용 변환 (모든 나라 가능)
std::locale loc("spanish");
const std::ctype<wchar_t>& ct = std::use_facet<std::ctype<wchar_t> >(loc);
std::wstring str3(L"pequeño");
std::transform(str3.begin(), str3.end(), str3.begin(), 
std::bind1st(std::mem_fun(&std::ctype<wchar_t>::toupper), &ct));
log("facet 이용 대소문자 변환=%s",str3.data());

// 반복자 이용한 출력
msg = "abcdefg";
string::iterator it;
cout<<"반복자 이용한 출력=";
for(it=msg.begin(); it!=msg.end(); ++it) {
cout<<*it;
}
cout<<endl;

// 모든 문자들의 순서 변경
msg = "gfedcba";
std::reverse(msg.begin(), msg.end());
log("순서 바꾸기=%s",msg.data());

// 문자 정렬
std::sort(msg.begin(), msg.end());
log("문자 정렬=%s",msg.data());

// 연속된 문자 제거
msg = "1223334444";
msg.erase(std::unique(msg.begin(), msg.end()), msg.end());
log("연속된 문자 제거=%s",msg.data());


}

//대문자를 소문자로 변환하는 함수 (영어만 가능)
char StringTest::toLower(char elem){
if(elem>='A' && elem<='Z')return elem+('a'-'A');
return elem;
}

//소문자를 대문자로 변환하는 함수 (영어만 가능)
char StringTest::toUpper(char elem){
if(elem>='a' && elem<='z')return elem-('a'-'A');
return elem;
}

//대 소문자 구별없이 일치여부 판단
char StringTest::equlasIgnoreCase(char c1, char c2){
return toUpper(c1)==toUpper(c2);

반응형

+ Recent posts