본문 바로가기
알고리즘 문제풀이/개념정리

[개념정리] C++ string 정리 -1

by 로디네로 2021. 3. 4.
반응형

String Library 란

 

문자열을 나타내기 위한 클래스 이다.

 

대체로 코딩테스트에 문자열 input을 받아 처리하는 문제가 나오면

 

처리가 쉬운 파이썬으로 풀기를 권장하지만

 

나머지 부분을 전부 c++ 로 준비했거나 직무가 c 관련이라서 이 글을 보시는 분도 계실것이다.

 

나도 또한 코딩테스트를 보다가 string에서 애먹은적이 있기 때문에 정리차원에서 적어본다.

 


 

String 초기화

주석참고

#include <iostream>
#include <string>
using namespace std;

int main(){
	// 1
    string str1 = "coding_ddunddun1";
    // 2
    string str2("coding_ddunddun2");
    // 3
    string str3;
    str3 = "coding_ddunddun3";
    // 4
    string str4;
    str4.assign("coding_ddunddun4");
    // 5
    string *str5 = new string("coding_ddunddun5");
    return 0;
}
    

 


 

String 크기

주석참고

#include <iostream>
#include <string>
using namespace std;
int main(){
	string str1 = "coding_ddunddun";
    // size 와 length 는 같은 역할을 수행한다.
    cout << str1.size() << endl;
    cout << str1.length() << endl;
    return 0;
}    

 


 

String Index

주석참고

#include <iostream>
#include <string>
using namespace std;
int main(){
	string str1 = "coding_ddunddun"; // 선언
    cout << str[0] << endl; // 0번째 글자 "c"
    cout << str.at[0] << endl; // 0번째 글자 "c"
    str.at[0] = 'D'; // coding -> Doding 으로 바뀔것
    cout << str.front() << endl; // 맨 첫번째 글자 'D'
    cout << str.back() << endl; // 맨 마지막 글자'n'
    return 0;
}

 


 

String 비교 연산

주석참고

#include <iostream>
#include <string>
using namespace std;
int main(){
	string str1 = "ABC";
    string str2 = "ABC";
    cout << (str1==str2) << endl; //1
    cout << (str1!=str2) << endl; //0
    
    string str3 = "CBA";
    if(str1<str3){ // ABC 와 CBA를 비교했을때 ABC가 사전적으로 앞이니 더 작다고 본다.
    	cout << 'str1 is small';
    }
    
    cout << str1.compare(str3) << endl; //똑같이 비교했을 때 str1이 더 작으므로 -1을 반환
    // 같다면 0을 str1이 더 크다면 1을 반환한다.
    return 0;
}

 


 

String 글자 추가

주석참고

#include <iostream>
#include <string>
using namespace std;
int main(){
	// + 로 나타내기
	string str1 = "A";
    string str2 = "B";
    string str3 = str1 + str2; //"AB"
    str3 += "C"; //"ABC"
    
    //append 로 나타내기
    str3.append("D"); //"ABCD"
    string str4 = "EDDDDDDD";
    str3.append(str4,0,1); //str3에 str4의 index 0부터 1칸 붙이기 "ABCDE"
    str3.append(5, '.'); //5개의 '.'을 붙인다. "ABCDE....."
    return 0;
}
    

 


String 문자 탐색

주석참고

#include <iostream>
#include <string>
using namespace std;
int main(){
	string str1 = "nice to meet you";
    string str2 = "to";
    cout << str1.find(str2) << endl; // 전체문장에서 to를 찾고 그 인덱스를 반환 = 5
    cout << str1.at(5) << endl; // 5번 인덱스에 있는 문자는 = t
}

 


 

계속된 포스팅에서 string 을 파악해보고자 한다.

반응형

댓글