알고리즘/알고리즘 관련 메모장

C++ string 사용법

잡담연구소 2020. 11. 9. 19:34

jhnyang.tistory.com/115?category=850633 1,2탄과 blockdmask.tistory.com/338en.cppreference.com/w/cpp/string/basic_string 를 참고했습니다.

 

C언어에서는 문자열을 입력받을 때, 문자열의 크기를 모르는 경우가 많았다. (내가 바보여서 그럴 수도 있음 ㅎㅎ )

그래서 보통 char sentence[100] 이런 식으로 두고 풀었었는데 c++에서는 string이라는 class를 사용하면 편리하게 문자열을 다룰 수 있다.

 

0. 기본

input ) 

#include<iostream>
#include<string> //string이라는 헤더파일을 불러온다.
using namespace std;

int main() {
	string sentence;  // 1
	//sentence = "Hi I am student!"

	//2
	getline(cin, sentence); 
	
	//3. size = length
	cout << "문자열의 크기:" << sentence.size() << endl; 
	cout << "문자열의 길이:" << sentence.length() << endl; 	
}

output )

내 얼마 안되는 경험상 보통 문자열은 입력을 받는 경우가 많았다. 고로 문자열의 길이도 몰랐다.

하지만 string을 이용하면 

//1 과 같이 string 클래스를 사용할 변수명을 정의해주자. 이때 sentence[100]마냥 안 써줘도 됨 ㅎㅎ

//2 getline이라는 함수를 이용해서 공백을 포함해서 문장을 입력받을 수 있다. 

//3 size , length : returns the number of characters

문자열.size() 와 문자열.length()는 같은 역할을 한다. 

입력받은 문자열에 대해 문자열의 크기 혹은 길이를 반환해준다. 

문자열에 대해 for문 사용할 때 특히 꿀이다 ㅎㅎ 

 

1. element access ( parameter : index)

input)

	// 4. at 사용
	cout << sentence.at(2) << endl;
	sentence.at(2) = '!';
	cout << sentence.at(2) << endl;

	// 5. operator 사용
	sentence[15] = '~';
	cout << sentence << endl;

	//6. front 와 back
	cout << sentence.front() << endl;
	cout << sentence[0] << endl;

	cout << sentence.back() << endl;
	cout << sentence[sentence.size()-1] << endl;

output)

//4. at : accesses the specified character with bounds checking

특정 인덱스에 접근하는 함수다. 

string도 배열처럼 index 0부터 시작하기때문에  Hi I am student! 를 생각해보면 인덱스 2번째는 현재 공백이다. 

at을 이용하여 sentence의 인덱스 2번째에 접근 후 '!'로 바꾸어주었다.

그 후 다시 sentence의 인덱스 2번째를 출력해보면 공백이 아닌 ! 로 바뀐 걸 확인할 수 있다. 

 

//5. accesses the specified character

그냥 인덱스를 가지고 배열에 접근하는 방식을 생각하면 된다. 

sentence[15] = '~'는 sentence의 15번째 인덱스에 접근해 기존 ! 였던 걸 ~ 로 바꾸어줄 수 있다. 

바뀐 문장을 출력해보면 student!가 아닌 student~로 바뀐 걸 확인할 수 있다.

 

//6. front & back : accesses the first/last character

말 그대로 맨 첫 번째 혹은 맨 마지막 인덱스에 위치한 문자에 접근한다.

 

front  = 0번째 인덱스 last = size()-1 번째 인덱스 (왜냐면 배열은 0부터 시작해서 맨 마지막 인덱스가  배열의 길이-1 이니까!)

 

이 외에도 data , c_str  등이 있는데 too hard to me,,,,,,ㅠ

 

2. Capacity 

input)

	//7. empty 
	cout << "empty:" << sentence.empty() << endl;
	
	//8. max_size
	cout << "Maximum size of a string is " << sentence.max_size() << endl;

	//9.capacity
	cout << "capacity:" << sentence.capacity() << endl;

	//10. shrink_to_fit
	sentence = "I am a student";
	cout << sentence<<endl;
	sentence.shrink_to_fit();
	cout << "capacity:" << sentence.capacity() << endl;

 

output)

//7. empty : checks whether the string is empty

string이 비어있으면 TRUE (1) , 비어있지 않으면  FALSE(0) 을 반환한다.

 

//8. max_size : returns the maximum number of characters

문자열의 최대 길이를 반환해준다.

쓸 일이 있을 거 같진 않다,,,,, 이걸 어따 써머거,,,,

 

//9. capacity : returns the number of characters that can be held in currently allocated storage

이 문자열에 할당된 메모리크기 (bytes)를 얘기한다.

지금 sentence가 "Hi I am student!" 으로 capacity가 31임을 알 수 있다.

 

//10. shrink_to_fit : returns the number of characters that can be held in currently allocated storage

쓸데없는 capacity 즉 , 메모리 사용을 줄여준다 .

지금 코드에 보면 "Hi I am student!" 를 "I am a student"로 sentence를 변경해주었다.

shrink_to_fit을 사용하여 사용하지 않는 불필요한 메모리를 줄인 후 다시 capacity를 출력해보면 15로 줄어든 걸 확인할 수 있다.

 

3. operations

input) 

	//11. clear
	sentence.clear();
	cout << "empty:" << sentence.empty() << endl;

	sentence  = "Hi I am student";

	//12. insert
	sentence.insert(8, "a ");
	cout << sentence << endl;

	//13. erase
	sentence.erase(0, 3);
	cout << sentence << endl;
	sentence.erase(5);
	cout << sentence << endl;

	sentence = "Hi I am student";

	//14.pushback & popback
	sentence.push_back('!');
	cout << sentence << endl;
	sentence.pop_back();
	cout << sentence << endl;

	//15.append
	sentence.append(5, '!');
	cout << sentence << endl;
	
	string hello = "nice to meet you";
	sentence.append(hello);
	cout << sentence << endl;
	
	sentence.append(sentence, 0, 2);
	cout << sentence << endl;

	sentence.append({ ' ','g' , 'o' , 'o' , 'd' });
	cout << sentence << endl;

	//16. + 
	sentence = "Hi I am student";
	sentence += hello;
	cout << sentence << endl;

	//17. compare
	sentence = "Hi I am student";
	
	cout << sentence.compare(hello) << endl;
	// Hi I am student vs nice to meet you
	cout << sentence.compare(8,7,hello) << endl;
	// student vs nice to meet you
	cout << sentence.compare(8, 7, hello,8,4) << endl;
	// student vs meet

	//18.replace
	cout << sentence.replace(8, 7, "girl") << endl;

	//19. substr
	cout << sentence.substr(8) << endl;
	cout << sentence.substr(3, 4) << endl;

	//20. swap
	sentence.swap(hello);
	cout << "sentence: " << sentence << endl;
	cout << "hello: " << hello << endl;

output) 

  //11. clear : clears the contents

모든 문자열을 지워준다. 코드를 보면 sentence.clear()를 통해 문자열을 지워준 후 empty로 확인을 해보면 1(True)가 나오는 것을 확인할 수 있다.

 

//12. insert : inserts characters

특정 인덱스에 특정 문자를 집어넣는다.

insert(8,"a")는 8번째 인덱스 자리에 a를 넣어달라! 라는 뜻이다.  Hi I am a student 로 바뀐 것을 확인할 수 있다.

 

//13. erase : removes characters 

문자열을 삭제해준다. 

erase(0,3) 같은 경우 erase(삭제를 시작할 인덱스 , 삭제할 문자 개수) 로 0번째 인덱스부터 3개의 문자를 지운다는 뜻이다. Hi I am student >>I am student 로 'Hi ' 공백까지 총 문자 3개가 삭제된 것을 확인할 수 있다.

erase(5) 처럼 삭제할 문자의 개수를 주지 않으면 그 이후로 다 지워버린다. 

I am student > I am 으로 5번째 인덱스에 위치한 s부터 그 이후를 다 지우는 걸 확인할 수 있다. 

 

//14. push_back : appends a character to the end

문자열의 맨 마지막에 문자를 새로 하나 추가해준다.

Hi I am student 라는 sentence에 push_back("!") 을 이용해 맨 마지막에 !를 추가해준다.

       pop_back : removes the last character

문자열의 맨 마지막 문자를 제거해준다. 문자가 무엇이든 상관없이 맨 마지막에 위치하기만 하면 삭제해주므로 추가할 문자를 parameter로 입력해줘야하는 push_back과는 다르게 parameter가 필요없다.

Hi I am student! 라는 문장에서 pop_back을 이용하여 맨 마지막에 위치한 ! 를 제거해주자

 

//15. append : appends characters to the end

문자열의 맨 뒤에 추가한다는 점이 push_back과 비슷하지만 차이점이 존재합니다. push_back은 "a character" 즉 한 문자만 뒤에 추가할 수 있지만 append는 "characters"로 여러 문자열을 추가 할 수 있습니다. 

코드를 한줄 한줄 다시 읽어보면

 

sentence.append(5,"!") -> append( 반복할 횟수 혹은 개수 , 추가할 문자 ) 로 !를 5번 추가해주겠다는 뜻입니다. 

 

hello라는 새로운 string에 nice to meet you라는 문자열을 넣어봅시다! 

sentence.append(hello) -> sentence.append( 또 다른 string ) 으로 string끼리 append해주는 역할을 합니다.

 

sentence.append(sentence,0,2) -> append(추가할 문자열 , 시작인덱스 , 갯수) 로 특정 문자열의 특정 부분만큼만 append하는 것도 가능합니다! 그럼 지금 sentence라는 특정 문자열에 대해 0번째 인덱스부터 두개니까 

Hi 라는 문자열이 append되겠네요 ㅎㅎ 

 

sentece.append( {' ','g' , 'o' , 'o' , 'd' }) -> 이런 방법도 가능합니다.  good 라는 문자열을 뒤에 append 해주고 싶으면 문자 각각 하나하나에 대해 추가해주면 됩니다.

 

//16. + : appends characters to the end

append와 동일합니다.  c와는 다르게 c++에서는 기본 연산자 오버로딩이 되어있기 때문에 +연산자를 사용할 수 있습니다. 아마 -연산자는 안되는 걸로 알고 있습니다 ㅎㅎ 

 

//17. compare : 

이 녀석은 c에서의 strcmp와 같은 역할을 합니다. 

a.compare(b)  는 '사전적'으로 a가 b 보다 더 앞에 있다면 -1 , 같다면 0 , 뒤에 있다면 1을 반환합니다. 

얘도 코드를 한줄한줄 살펴보자면 

 

sentence.compare(hello) : sentece라는 string과 hello라는 string을 비교합니다. 즉 "Hi I am student!" 라는 문장과 " nice to meet you"를 사전적으로 비교하면 sentence가 더 먼저겠죠? 그렇기에 -1을 출력합니다 .

 

sentence.compare(8,7,hello)는 sentece문장의 8번째 인덱스부터 시작해 문자 7개를 hello와 비교한다는 뜻입니다. 

즉, student와 nice to meet you를 비교하는거죠. 이 경우 nice가 더 사전적으로 먼저 나오기에 1을 출력합니다. 

 

sentence.compare(8,7,hello,8,4)도 그렇다면 유추해볼수 있겠죠? string의 8번째 인덱스부터 문자 7개 와 hello의 8번재 인덱스부터 문자 4개를 비교하는겁니다. 그러면 student와 meet을 비교하는게 됩니다. 사전적으로 meet이 더 먼저니까 1을 반환하겠네요 

 

//18. replace : replaces specified portion of a string

말 그대로 문자열의 특정 부분을 바꿔주는겁니다. 

sentence.replace(8, 7, "girl") 인 경우 기존 sentence 문장의 8번째 인덱스부터 7개를 girl로 바꿔준다는겁니다. 

hi i am student >> hi i am girl 로 바뀌겠네요

 

//19. substr : returns a substring

문자열의 특정 부분(substring)을 반환해줍니다. 

sentence.substr(8) 의 경우 sentence라는 스트링의 8번째 인덱스 이후부분을 반환합니다. 

출력해보면 girl 이 나오는 것을 확인할 수 있습니다.

sentence.substr(3,4)는 3번째 인덱스부터 4개의 문자를 반환 ! 그러면 i am이 나오겠네용

 

//20. swap : swaps the contents

stirng에 할당된 문자열을 서로 뒤바꿔줍니다.

출력결과를 보면 hello라는 스트링과 sentence 라는 스트링의 내용이 서로 뒤바뀐 것을 확인할 수 있습니다.

 

 

4. search 

input) 

	//21. find , rfind
	sentence = "This is a string";
	hello = "nice to meet you!";

	cout << sentence.find("i") << endl;
	cout << sentence.find("is")<<endl;
	cout << sentence.find("is", 5) << endl;

	cout << sentence.rfind("i") << endl;
	cout << sentence.rfind("is") << endl;
	cout << sentence.rfind("is", 5) << endl;

output)

find 보자마자 뭔가 유용하게 잘 쓸 수 있을 거 같다는 예감이 듭니다 ㅎㅎ 아니면 말구요 뭐 

 

//21. find : find characters in the string

       rfintd : find the last occurrence of a substring

 

parameter로 입력한 문자가 주어진 string안에 있는지 확인하는 함수입니다. 

기본적으로 find는 맨 앞에서부터 찾아내고 , rfind는 맨 뒤에서부터 찾아냅니다.

코드 설명을 좀 해보자면 

 

sentence.find("i") : sentence라는 스트링 내에서 i라는 문자가 몇 번째 인덱스에서 처음으로 나오는 지 알려줍니다. 

제가 sentence = "This is string"으로 바꿨으니까 i가 처음 나오는 인덱스느 2겠죠???sentence.find("is") : 오! 문자만 되는게 아니라 문자열도 찾을 수 있습니다. 똑같이 is라는 문자열은 인덱스2부터 시작하니 2를 출력하네요 

sentence.find("is" , 5) : is라는 문자열을 찾되 5번째 인덱스에서 시작해서 찾겠다! 라는 뜻입니다. 기본적으로 맨 앞, 인덱스0 부터 찾는데 이렇게 find를 시작할 인덱스 번호를 파라미터로 줘서 변경할 수도 있습니다. 그럼 5번째 인덱스가 i니까 5가 출력이 되겠네요! 

 

sentence.rfind("i") : 맨 뒤에서부터 찾습니다. 그러면 string의 i가 젤 처음으로 등장하겠네요 인덱스 13이 출력됩니다.

sentence.rfind("is") : 맨 뒤 기준으로 is가 처음 등장하는 곳은 5번째 인덱스겠네요.

sentence.rfind("is",5) : 동일합니다. 인덱스 5부터 is가 있는 곳을 찾습니다. 그럼 인덱스 5부터 인덱스0까지 거꾸로 탐색을 하겠죵?

 

 

제 실력이 부족해서 아직 생성자 관련해서는 포스팅 하지 않았습니다.

실력이 좋아지면 그때 다시 포스팅하도록 하죠 ㅎㅎ 

그럼 이제 백준 풀러 가봅시당~!~