본문 바로가기

언어/C++

[C++ 개념] 2. 문자열의 활용

1. String 클래스

연산자

  • C의 "char*" 과 비교했을 때, string형은 많은 장점을 가짐
char *a = "hello";
char *b = "hello";

if (a == b)
{
	//something
}
  • 위의 결과는 if 문의 something을 실행하지 않는 것이다.
    • 이유 - "내용"을 비교하는 것이 아니라 "포인터"를 비교하는 것이기 때문
    • 따라서 strcmp(a, b) 를 활용해서 비교해야 함(같다면 0)
  • 하지만, string의 경우 결과가 달라짐
std::string a = "hello";
a += ", world";
std::string b = a;

if ( a == b )
{
	b[0] = 'H';
}

std::cout << a << std::endl;
std::cout << b << std::endl;
  • 위의 결과는 (a = hello, world / b = Hello, world)가 됨
    • 이 외에도 다른 비교 연산자문자열 연산이 가능
  • 또한 string은 Memory Leak(메모리 누수)가 발생하지 않음
    • 범위를 벗어나게 되면 소멸자가 호출되어 알아서 관리해줌

 

변환해주는 함수 목록

함수 기능
std::to_string
(int / unsigned / long / unsigned long / long long /
unsigned long long / float / double / long double )
숫자들을 string 형으로 변환 시켜 줌
std::stoi(const string &str, size_t *idx=0, int base = 10); idx - 변환에 실패한 첫 번째 문자의 인덱스를 리턴
base - 진수를 선택할 수 있음(2진수 / 10진수 등)
string -> int 변환
std::stol(const string &str, size_t *idx = 0, int base = 10); string -> long 변환
std::stoul(const string &str, size_t *idx = 0, int base = 10); string -> unsigned long 변환
std::stoll(const string &str, size_t *idx = 0, int base = 10); string -> long long 변환
std::stoull(const string &str, size_t *idx = 0, int base = 10); string -> unsigned long long 변환
std::stof(const string &str, size_t *idx = 0, int base = 10); string -> float 변환
std::stod(const string &str, size_t *idx = 0, int base = 10); string -> double 변환
std::stold(const string &str, size_t *idx = 0, int base = 10); string -> long double 변환

 

로우 문자열 리터럴(Raw String Literal)

  • "\t", "\n"과 같은 역슬래시(\)를 통한 이스케이프 시퀀스를 일반 문자열로 취급
  • 따라서 아래와 같은 코드는 Compile Error가 발생
std::string a = "My Name Is "Hong Gil-dong"";
  • 이스케이프 처리가 되지 않은 따옴표가 문자열 안에 들어가 있기 때문이다.
    • 문자열 안에서 따옴표(")를 쓰고 싶을 경우 (\")로 써주어야 함
    • 또는 R"(My Name Is "Hong Gil-dong")" 으로도 가능
  • 로우 문자열 리터럴을 사용하게 되면 여러 줄에 걸쳐 작성할 수 있음
// compile error
std::string a = "code code1
code code 2 \t";

// OK
std::string b = R"(code code1
code code2 \t)";

// output
code code1
code code2 \t
  • 위와 같이 줄 바꿈은 결과에 반영되었지만, "\t"의 경우는 반영이 되지 않았음
    • 이스케이프 문자를 취급하지 않기 때문
  • 로우 문자열을 사용할 때 조심해야 할 점은 문자열 안에 ")"를 사용할 수 없다는 것

'언어 > C++' 카테고리의 다른 글

[C++ 개념] 3. 코딩 스타일  (0) 2021.12.01
[C++ 개념] 1. STL 부딪혀보기  (0) 2021.08.15