7. c++ STL string

han811·2021년 2월 10일
0

c++

목록 보기
7/14
post-thumbnail
1. size()
#include <iostream>
#include <string>

using namespace;

int main(void)
{
	string s = "assd";
    cout << s.size() << '\n';

	return 0;
}
  • 해당 문자열의 길이 반환
2. 문자열 -> 정수

stoi : string to int
stol : string to long
stoll : string to long long
stof : string to float
stod : string to double
stold : string to long double
stoul : string to unsigned long
stoull : string to unsigned long long

3. 정수 -> 문자열

to_string

4. char 배열 -> string
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	char ch[10] = "hello";
    string s1(ch);
    string s2 = ch;
    cout << s1 << " " << s2 << '\n';

	return 0;
}
5. string -> char 배열
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string s = "hello";
    char ch[10];
    strcpy(ch, s.c_str());
    
    cout << ch <<'\n';

	return 0;
}
  • string의 경우 내부에 char array를 가지고 있어서 .c_str()를 하면 const char* 형식의 값을 반환합니다.
  • 그래서 값을 변경하고싶다면 strcpy를 해주도록 합시다.
6. 문자열 일부 추출
#include <iostream>
#include <string>

int main() {
  std::string a = "0123456789abcdefghij";

  // count 가 npos 이므로 pos 부터 문자열 끝까지 리턴한다.
  std::string sub1 = a.substr(10);
  std::cout << sub1 << '\n';

  // pos 와 pos + count 모두 문자열 범위 안이므로, 해당하는 부분 문자열을
  // 리턴한다.
  std::string sub2 = a.substr(5, 3);
  std::cout << sub2 << '\n';

  // pos 는 문자열 범위 안이지만, pos+count 는 밖이므로, pos 부터 문자열 끝까지
  // 리턴한다.
  std::string sub4 = a.substr(a.size() - 3, 50);
  std::cout << sub4 << '\n';

  try {
    // pos 가 문자열 범위 밖이므로 예외를 발생시킴.
    std::string sub5 = a.substr(a.size() + 3, 50);
    std::cout << sub5 << '\n';
  } catch (const std::out_of_range& e) {
    std::cout << "pos exceeds string size\n";
  }
}
7. string::find, string::npos
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string str = "hello world";
    if(str.find("world") == string::npos){
    	cout << "true" << '\n';
    }
	return 0;
}
  • find를 사용하면 해당 문자열이 찾아지는 가장 앞의 인덱스를 반환합니다.
  • string의 position 값이 없다면 std::string::npos를 반환합니다.
  • s.find(c, 4)는 문자열 s에서 4번째 부터 c를 검색하라는 뜻이 됩니다.
8. 일반적인 string의 대소 비교
  • <,>로 연산자 오버로딩이 되어 있으며 사전식 배열 비교가 이루어 집니다.
9. memset, sizeof, strlen
  • 사실 해당 함수들은 배열을 다룰 때 자주 사용하게 되는데 c스타일의 문자열들은 const char 형의 배열로 표현이 되므로 해당 함수들에 대해 잘 알 필요가 있습니다.
#include <iostream>
#include <string>

int main(void)
{
    int arr[5];
    memset(arr, 1, sizeof(arr));
    for (int i = 0; i < 5; ++i)
    {
        cout << arr[i] << '\n';
    }
    return 0;
}
  • 위와 같이 memset을 이용하면 연속된 주소의 값을 초기화가 가능합니다.
  • strlen은 char형의 배열 문자열에 대해서 문자열의 길이를 구해주는 함수로 마지막의 null 문자 '\0'은 포함하지 않습니다.
  • sizeof는 피연산자의 메모리 크기를 바이트 단위로 계산하여 반환해 줍니다.
profile
han811

0개의 댓글