07
30

1. .length()

문자열의 길이 반환, 공백 포함, null 문자 미포함

int solution(string message) {
	//입력받은 string 문자열 message의 길이를 출력한다
	//the apple을 입력받았다면 9를 출력할 것이다
    return message.length();
}

2. .size()

현재 사용하고 있는 메모리의 크기 반환, null 문자 포함, 하지만 string에서는 문자열 끝에 null 문자를 포함하지 않으므로 length와 같게 나옴

3. .erase(first,last)

first 부터 last 전까지 범위의 요소를 제거한다

//the apple -> e apple
int solution(string message) {
    message.erase(message.begin(),message.begin()+2);
    return message;
}

4. .substr(pos, count)

문자열의 pos 번째 문자 부터 count 길이 만큼의 문자열을 리턴한다.

#include <string>
#include <vector>

using namespace std;

//my_String의 앞에서부터 n글자를 반환
string solution(string my_string, int n) {
    return my_string.substr(0,n);
}

5. .find(str)

문자열에서 str의 위치를 리턴한다. 없으면 string::npos를 반환한다

비슷하게 rfind(str) 함수는 문자열에서 str 위치를 리턴하되 뒤에서부터 찾는다.

#include <string>
#include <vector>

using namespace std;

//문자열 str2에 문자열 str1을 포함할 경우 true를 반환
int solution(string str1, string str2) {
    return str2.find(str1) != string::npos;
}

6. .replace(pos, count, str)

문자열에서 pos부터 시작하는 count 개수의 문자열을 str로 대체한다

#include <string>
#include <vector>

using namespace std;

//문자열 my_string의 s부터 overwrite_string으로 덮어씌운다
string solution(string my_string, string overwrite_string, int s) {
    my_string.replace(s, overwrite_string.size(), overwrite_string);
    return my_string;
}

'C++ > 자료노트' 카테고리의 다른 글

<numeric>  (1) 2023.10.31
기타 유용한 함수 등등  (0) 2023.08.08
<vector>  (0) 2023.07.30
<algorithm>  (0) 2023.07.30
COMMENT