string class를 이용한 문자열

shinyeongwoon·2022년 11월 22일
0

C++

목록 보기
3/10

C++ 문자열

  • C - 스트링
  • C++ string 클래스의 객체

String 클래스

  • c++ 표준 라이브러리, \ 헤더 파일에 선언
#include <string>
using namespace std;
  • 가변 크기의 문자열
string str = "I love ";
str.append("C++");
  • 다양한 문자열 연산을 실행하는 연산자와 멤버 함수 포함
    문자열 복사, 문자열 비교, 문자열 길이 등
  • 문자열, 스트링, 문자열 객체, string 객체 등으로 혼용

문자열 생성

// 빈 문자열을 가진 스트링 객체
string str;
// 문자열 리터널로 초기화
string address("청주");
// address를 복사한 copyAddress
string copyAddress(address);

//C-스트링(char [] 배열)으로 스트링 객체 생성
char text[] = {'L','O','V','E'};
//"LOVE" 문자열을 가진 title 생성
string title(text);

문자열 출력

cout 과 << 연산자

cout << address << endl;
cout << title << endl;

문자열 입력

cin 과 >> 연산자

string name;
cin >> name; //공백이 입력되면 하나의 문자열로 입력

문자열 숫자 변환

stoi() 함수 이용 2010 버전 이상

string s = "123";
int n = stoi(s);

atoi 2008 이하

string s = "123";
int n = atoi(s.c_str());

new / delete 를 이용하여 문자열을 동적 생성 / 반환 가능

string *p = new string("c++");

cout << *p; //"c++" 출력
p -> append("Great");	
cout << *p; //"c++ Great" 출력

delete p;

예제)

#include <iostream>
#include <string>

using namespace std;

int main(){
  string names[5];
  for (int i =0 ; i < 5 ; i++)
    getline(cin,names[i],'\n');

  string latter = names[0];
  for(int i = 1; i < 5 ; i++){
    if(latter < names[i]){
      latter = names[i]
    }
  }
  cout << "사전에서 가장 뒤에 나오는 문자열은" << latter << endl;

}
  • 문자열 길이
int len = s.length(); 
  • 문자열 자르기 및 연결하기
string first = s.substr(0,1);

string sub = s.substr(1, len-1); 

s = sub + first; 
  • 문자열 찾기
int fIndex = s.find('+', startIndex)
  • cin.ignore()
getline(cin, s, '&'); // 문자열 입력

cin.ignore(); // &뒤에 따라오는 엔터를 제거하기 위한 코드
  • replace() 함수
s.replace(fIndex, f.length(), r); // fIndex부터 문자열 f의 길이만큼 문자열 r로 변경

0개의 댓글