programming/C++

[C++] String class

KoTiv 2021. 12. 24. 12:04
반응형
SMALL

2021.12.24 - [programming/Language] - [C++] STL Container 특징 과 String class

 

[C++] STL Container 특징 과 String class

STL(Standard Template Librate ) 란 ? C++ 템플릿을 이용한 표준으로 정리된 라이브러리로 구성요소로 반복자, 컨테이너, 알고리즘을 3가지 구성요소로 가지고있다. ** string 은 c++ 표준라이브러리로 STL에

hofe-rnd.tistory.com

STL에 대하여 전체적으로 정리를 했으니 이제 전체 내용의 한요소요소를 뜯어보고자 한다 

STL Container와 다르지만 문자열 처리에 필요한 String class에 대해 먼저 기술한 이후 차근차근 STL Container 요소를 알아 보자.

 

C++ String 

String은 c++에서 표준 라이브러리로 STL에 포함되지 않는다.

String은 문자만을 원소로 저장하고 문자열을 조작할 목적으로 사용되는 컨테이너로 String을 사용하기 위해서는

<string> 헤더를 지정해주어야 사용할수 있다.

 

생성자 사용방법 정리

생성자 description
string s 기본 생성자로 string s 생성
string s(str) str문자열로 string s 생성
string s(str, n) str 문자열에서 n개의 문자열로 string s를 생성
string s(n, c ) n개의 c문자로 string s를 생성
string s(iter1, iter2) 반복자 구간 [iter1, iter2) 의문자로 string s 생성
string s(p1, p2) 포인터 구간 [p1, p2)의 문자로 stinrg s를 생성

 

멤버함수 정리

string s = "hello"; , string s2 = "world" 인 기본생성자 s, s2를 사용하여 스트링 멤버함수를 정리한다면 아래의 표와같이 정리할 수 있으며  붉은색 멤버함수는 자주쓰는 함수라고 생각한다 .

멤버함수 함수원형 description 비고
at(index)

인자접근멤버
char& at(size_t index) . index에 숫자가 들어감
. index에 해당하는 문자 반환.
. index는 0부터 시작.
.
index 범위가 넘어서면 예외처리
s.at(0); 
-> h를 반환
operator[index]

인자접근멤버
char& operator[](size_t index) . 배열처럼 []을 이용하여 string인자 접근
. at과간이 index범위를 검사하지 않음
. 즉 at보다 속도가 빠름 
. 예외를 처리하지않음
s[0];
-> h를 반환
front()

인자접근멤버
char& front(); . string의 맨 앞 인자를 반환. s.front();
-> h를 반환
back()

인자접근멤버
char& back(); . string의 맨 뒤 인자를 반환.
. 사용을 많이함
s.back()
-> o 반환
size()

size 관련
size_t size() const; . string 사이즈를 반환. s.size();
-> 5
length()

size 관련
size_t length() const; . string 길이를 반환 s.length();
->5
capacity();

size 관련
size_t capacity const; . string 객체에 할당된 메모리 크기
(byte)를 반환.
. vector의 capacity와 마찬가지로 길이 증가이유로 메모리 할당을 여유롭게한다.
. size가 capacity를 넘길때 새롭게 더큰 
capacity를 할당하게됨.
s.capacity()
-> 10
resize(n);

size 관련
void resize( size_t n),
void resize(sizt_t n, char c );
. string을 n만큼의 크기로 만듬.
. 해당 크기가 원 사이즈보다 작으면 
남은 스트링을 버림
. 크기가 원사이즈보다 크다면 빈공간으로 남은 공간을 채움,
. 만약 c를 사용하면 남은공간은 c로 채움, 
. c를 사용시 중간에 빈캄은 q를 추가했던것.

s.resize(4);
-> hello->hell
s.reszie(7);
->hello-> "hello  "
s.resize(7.1);
->hello->hello 11
shrink_to_fit()

size 관련
void shrink_to_fit() . String 길이에 비해 낭비되는 capacity를 줄이는 함수. . s.shink_to_fit();
->5
s.capacity()시 10이었던 값이 5로 줄어듬
reserver(n)

size 관련
void reserve(size_t n = 0) . 문자열을 넣 기전 미리 n의 사이즈만큼 capacity를 할당하는 함수.
. 주로 파일 읽을때 사용하게됨.
. while( !eof)를 하여 파일 한글자식 읽을때 eof를 활용하여 끝까지 읽게되는데 
이때 미리 메모리를 할당하여 capacity의 사이즈가 계속 늘어나는 상황을 방지하여 성능저하를 막는 역할을함.
s.reserve(10)
clear()
size 관련
void clear() . String에 들어있는 문자열을 지우는 함수
. size , length는 0이되고 capacity는 그대로 할당된상황이다.(메모리 해제가 아님)
s.clear()
empty()
size 관련
bool empty() const; . String이 비어있는지 확인하는 함수.
. 비었으면 True, 
. 빈 기준은 size , length == 0 으로 판단
. capacity와는 연관성이 없음.
 
c_str() const char* c_str() const; . C++ String 문자열을 C스타일 문자열로 변경 char *arr = s.c_str();
->hello ->hello\n
으로 반환해줌
substr() string substr(size_t index =0 , 
      size_t len =npos) const;
. string을 index에서부터 len만큼 잘라서 반환.
. len의 default npos의 의미는 -1.
. size_t의 type은 unsigned int type.
>> unsigned int == -1 은 언더플로우 
즉 제일 큰값으로 세팅이됨.
그의미는 문자열이 길어질 수 있는 최대의 길이값을 의미하게됨.
s.substr(2)
->hello에서 
llo를 반환하게됨.
s.substr(2,1)
l 반환
2의index자리에서 1의 길이만큼 반환.
replace() string& replace(size_t index,
      size_t len, const string& str)
. 함수를 호출하는 문자열의 index위치에서 len의 길이까지 범위를 변수로 들어온 str 전체로 대체하는 함수 .  s.replace(2,2,s2);
-> hello에서 
"ll"의 위치에 
s2의 "world"가 들어가
heworldo의 문자가 형성됨.

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;

. 매개변수로 들어온 str을 비교하여 같으면 0 다르면 0이아닌 값을 반환하는 함수

 
copy() size_t copy(char* arr, size_t len,
           size_t index = 0) const;
. 문자열 복사함수. 
. char* arr ; 호출한 문자열을 arr에 복사
. len 복사할 문자열 길이
. index 복사할 위치
char arr[10]; 배열생성
int arrlen =s.copy(arr,2,2);
// index2부터 길이2만큼 복사  hello
arr[arrlen]='\0'; 

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

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

. 매개변수로 들어온 문자열과 , 자신의 문자열중 일치하는 문자가 있는지 확인하는 함수. 
. 일치시 일치하는 첫 index 반환
. index매개변수는 찾는 시작위치를 설정하는 offset으로 보면된다.
 
push_back() void push_back(char c); . 함수를 호출하는 스트링의 맨뒤에 문자를 더해주는 함수 s.push_back('a')
>helloa
pop_back() void pop_back() . 함수를 호출하는 스트링의 맨뒤에 있는 문자 하나를 삭제하는 함수. s.pop_bakc();
->hell
begin() iterator begin(); . 문자열의 첫 번쨰 문자를 가리키는 반복자를 반환함  
end() iterator end(); . 문자열의 마지막의 바로 다음을 가리키는 반복자를 반환. (끝이 아님)  
swap() void swap(string& str1, string& str2);

. s1과 s2를 바꾸는 함수. 
. 서로 참조하여 교환함.
 
append() string& append(const string& str);

. 문자 추가함수   
assign() string& assign( const string& str) . 문자 추가 함수  
data() const char*data() const noexcept; . Get string data  
insert() string& insertsize_t pos,
           const string &str)
. 문자열에서 원하는 위치에 문자열 추가  
erase() string& erase( size_t pos= 0 ,
     size_t len= npos)
. 문자열 삭제함수  
operator + string 끼리 더할 수 있는 operator    

 

reference

http://www.cplusplus.com/reference/string/string/

 

string - C++ Reference

 

www.cplusplus.com

 

 

반응형
LIST