프로그래밍 언어/C++

String 클래스

당장하자 2022. 3. 9. 23:42

std::String

  • C++ STL에서 제공하는 문자열을 관리하는 클래스이다.
  • 기존 C, C++에서 char 포인터를 이용해서 문자열을 관리하던 것을 포함하여 많은 일을 할 수 있다.
  • 문자열의 길이를 동적으로 초기화, 변경, 가능하다.
  • 문자열의 끝에 '널' 문자가 없다.

Q. <iostream>과 <string> 둘 중 하나만 포함해도 되는가?

A. <iostream>에 <string>이 포함되어있다.

하지만 어떤 이유로든 <iostream>을 지우게 될 수 있으니 <string>을 포함하는 것은 좋은 습관이다.

생성자 (Constructors)

// string constructor
#include <iostream>
#include <string>

int main ()
{
  std::string s0 ("Initial string");

  // constructors used in the same order as described above:
  std::string s1 = s0;
  std::string s2 (s0);
  std::string s3 (s0, 8, 3);
  std::string s4 ("A character sequence");
  std::string s5 ("Another character sequence", 12);
  std::string s6a (10, 'x');
  std::string s6b (10, 42);      // 42 is the ASCII code for '*'
  std::string s7 (s0.begin(), s0.begin()+7);

  std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
  std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6a: " << s6a;
  std::cout << "\ns6b: " << s6b << "\ns7: " << s7 << '\n';
  return 0;
}
s1: Initial string
s2: Initial string
s3: str
s4: A character sequence
s5: Another char
s6a: xxxxxxxxxx
s6b: **********
s7: Initial

 

입출력

std::string str;
getline(std::cin, str, 'a');	// 'a'가 나오기전까지의 문자열을 입력받는다.
getline(std::cin, str); // = getline(cin, str, '\n');

cin >> str;	// 공백 이전까지의 문자열을 입력받는다
cout << str;	// 문자열을 출력한다.

 

 

string 클래스 연산자

  • 비교연산자 (<, >, ==): 두 문자열의 사전 순서를 기준으로 비교한다.
  • 더하기연산자(+): 두 문자열을 이어준다.
std::string str1 = "abc";
std::string str2 = "defg";
std::string str3 = "abcdefg";

if(str3 == str1 + str2)
	std::cout << "같다" << std::endl;
else
    std::cout << "다르다" << std::endl;
    
// 같다 가 출력된다.

 

string 멤버함수

C++ Reference를 참조해서 적을예정

 

 

출처:

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

 

string - C++ Reference

 

www.cplusplus.com

 

https://en.cppreference.com/w/cpp/string

 

Strings library - cppreference.com

The C++ strings library includes support for three general types of strings: std::basic_string - a templated class designed to manipulate strings of any character type. std::basic_string_view (C++17) - a lightweight non-owning read-only view into a subsequ

en.cppreference.com

https://rebro.kr/53

 

[C++] string (문자열) 클래스 정리 및 사용법과 응용

[목차] 1. string 클래스란? 2. string 클래스의 입출력 3. string 클래스 생성 4. string 클래스 연산자 활용 5. string 클래스의 멤버 함수 6. string 클래스의 멤버 함수 사용 예시 1. string 클래스란? - C++..

rebro.kr