[C++] string (문자열) 클래스

Yewon Choi·2020년 6월 22일
1

C++

목록 보기
4/9

헤더파일 : #include <string>

생성방법 1: string str1("hello");

생성방법 2: string str2 = "hello";

생성방법 3: string str3(str1);

string 인자 접근관련 (access)

str1.at(index)

  • char& at (size_t index)
  • str1.at(0) -> 'h'

str1.operator[index]

  • char& operator[size_t index]
  • str1.operator[0] -> 'h' == str1[0] -> 'h'

str1.front()

  • char& front()
  • str1.front() -> 'h'

str1.back()

  • char& back()
  • str1.back() -> 'o'

string size 관련

str1.size()

  • size_t size() const 사이즈 반환
  • str1.size() -> 5

str1.length()

  • size_t length() const 길이 반환
  • str1.length() -> 5

str1.capacity()

  • size_t capacity() const 할당된 메모리 크기(bytes) 반환.
  • str1.capacity()

str1.resize(n)

  • `void resize(size_t n, char c). n만큼의 크기로 만듦.

str1.shrink_to_fit()

  • void shrink_to_fit() 낭비되고 있는 capacity(메모리)를 줄임

str1.reserve(n)

  • void reserve(size_t n = 0) 파일 읽을 때 많이 사용. 미리 메모리를 할당해, capacity가 사이즈에 맞게 계속 늘어나는 행위를 덜하게해서 성능저하를 줄임. (성능저하 예시, 노래방2인실->4인실->8인실)

str1.clear()

  • void clear()

str1.empty()

  • bool empty() const 비었
  • 는지 확인. 기준 : size, length가 0 (* capacity는 무관). 비었으면 true 리턴.

string 가지고 놀기

str1.c_str()

  • const char* c_str() const string 마지막에 \0를 추가. c언어처럼 바뀜.

str1.substr(....)

  • string substr(size_t index = 0, size_t len = npos) const index에서부터 len만큼 잘라서 반환

str1.replace(....)

  • string& replace(size_t index, size_t len, const string& str)
  • index 위치에서 len 길이까지의 범위를 매개변수로 들어온 str로 대체
  • str1.replace(5, 2, str2) / "BlockDMask" -> BlockBlogBlogBlogBlogask

str1.compare(....)

  • int compare(const string& str2) const
  • int compare(size_t index, size_t len, const string& str2) const
  • int compare(size_t index, size_t len, const string& str2, size_t index2, size_t len2) const

str1.copy(....)

  • size_t copy(char* arr, size_t len, size_index = 0) const

  • char arr[10];
    int arrLen = str1.copy(arr, 3, 5);  //arrLen== 3, arr == 'Mas'
    arr[arrLen] = '\0';   //arr == 'Mas\0'

str1.find(....)

  • size_t find (const string& str, size_t index = 0) const

  • size_t find (const char* arr, size_t index = 0) const

  • 일치하는 부분의 첫번째 순서(index) 반환

  • str2.find("Blog")  // 0반환
    str2.find("Blog", 5) //8반환 BlogBlogBlogBlog 5번째가 'l'로 다르니 그 다음 Blog의 B index

str1.push_back(c)

  • void push_back(char c)
  • 함수를 호출하는 string의 맨 뒤에 문자 c를 더함

str1.pop_back()

  • void pop_back()
  • 함수를 호출하는 string의 맨 뒤에 문자 하나 없앰

string iterator 종류

str1.begin()

  • iterator begin()
  • 문자열의 첫 번째 문자 가리킴

str1.end()

  • iterator end()
  • const_iterator end() const
  • 문자열의 지막의 바로 다음

string의 기타

swap(str1, str2)

  • void swap (string& st1, string& str2)
  • str1과 str2 바꾸는 것. 복사 아닌 참조를 교환해 성능저하 X

string 예제 구현코드

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

int main(void){
	string str1 = "BlockDMask";
	string str2 = "BlogBlogBlogBlog";
	
	
	//push_back, pop_back
	str1.push_back('4');
	cout << str1 << endl;
	//str1.pop_back();
	//cout << str1 << endl;
	
	// str2.resize(4);  //Blog 4 4 16
	//str2.shrink_to_fit(); //
	//str2.clear(); // 0 0 16
	int size = str2.size();
	int length = str2.length();
	int capacity = str2.capacity();
	cout << str2 << ' ' << size << ' ' << length << ' ' << capacity << endl;
	//BlogBlogBlogBlog 16 16 16
	
	//find
	cout << str1.find("DM") << endl;  //5
	cout << str2.find("Blog") << endl;  //0
	cout << str2.find("Blog", 5) << endl;  //8
	
	// operator[], atr
	cout << str1[0] << endl;  //B
	cout << str1.at(0) << endl;  //B
	
	//front, back
	//cout << str1.front() << endl;  //B
	//cout << str1.back() << endl;  //k
	
	//iterator begin(), end() // B l o c k D M a s k 4
	string::iterator iter = str1.begin();
	for(; iter != str1.end(); ++iter){
		cout << *iter << ' ';
	} 
	cout << endl;
	
	
	system("pause");
	return 0;
}
profile
https://github.com/devAon 찰나의 개발흔적을 남기는 개발블로그 입니다 🐥 https://aonee.tistory.com 에서 Velog로 블로그 이전 작업중입니다 ! 🎶

0개의 댓글