C++ 메모장

stringstream

lgbl 2025. 2. 25. 10:03

https://school.programmers.co.kr/learn/courses/30/lessons/150370

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

본 메모는 프로그래머스 '개인정보 유효기간' 문제 풀이 이후 정리함

 

  • 개인정보 유효기간
더보기

문제:

고객의 약관 동의를 얻어서 수집된 1~n번으로 분류되는 개인정보 n개가 있습니다. 약관 종류는 여러 가지 있으며 각 약관마다 개인정보 보관 유효기간이 정해져 있습니다. 당신은 각 개인정보가 어떤 약관으로 수집됐는지 알고 있습니다. 수집된 개인정보는 유효기간 전까지만 보관 가능하며, 유효기간이 지났다면 반드시 파기해야 합니다.
예를 들어, A라는 약관의 유효기간이 12 달이고, 2021년 1월 5일에 수집된 개인정보가 A약관으로 수집되었다면 해당 개인정보는 2022년 1월 4일까지 보관 가능하며 2022년 1월 5일부터 파기해야 할 개인정보입니다.
당신은 오늘 날짜로 파기해야 할 개인정보 번호들을 구하려 합니다.
모든 달은 28일까지 있다고 가정합니다.

오늘 날짜를 의미하는 문자열 today, 약관의 유효기간을 담은 1차원 문자열 배열 terms와 수집된 개인정보의 정보를 담은 1차원 문자열 배열 privacies가 매개변수로 주어집니다. 이때 파기해야 할 개인정보의 번호를 오름차순으로 1차원 정수 배열에 담아 return 하도록 solution 함수를 완성해 주세요.

 

제한사항

  • today는 "YYYY.MM.DD" 형태로 오늘 날짜를 나타냅니다.
  • 1 ≤ terms의 길이 ≤ 20
  • 1 ≤ privacies의 길이 ≤ 100
  • today와 privacies에 등장하는 날짜의 YYYY는 연도, MM은 월, DD는 일을 나타내며 점(.) 하나로 구분되어 있습니다.
  • 파기해야 할 개인정보가 하나 이상 존재하는 입력만 주어집니다.

#include <string>
#include <vector>
#include <unordered_map>
#include <sstream>

using namespace std;

// 날짜를 총 일수로 변환하는 함수
int convertToDays(const string& date) 
{
    int year = stoi(date.substr(0, 4));
    int month = stoi(date.substr(5, 2));
    int day = stoi(date.substr(8, 2));
    return (year * 12 * 28) + (month * 28) + day;
}

vector<int> solution(string today, vector<string> terms, vector<string> privacies) 
{
    vector<int> answer;
    
    // terms를 unordered_map으로 변환
    unordered_map<string, int> termsMap;
    for (const string& term : terms) 
    {
        stringstream ss(term);
        string type;
        int duration;
        
        ss >> type >> duration;
        termsMap[type] = duration;
    }
    
    // 오늘 날짜를 일수로 변환
    int todayInDays = convertToDays(today);
    
    // privacies 검사
    for (int i = 0; i < privacies.size(); i++) 
    {
        string privacy = privacies[i];
        
        // 수집 날짜와 약관 종류 파싱
        string date = privacy.substr(0, 10);
        string termType = privacy.substr(11);
        
        // 수집 날짜를 일수로 변환
        int collectedDay = convertToDays(date);
        
        // 만료 날짜 계산
        int expiryDate = collectedDay + (termsMap[termType] * 28);
        
        // 오늘 날짜와 비교
        if (todayInDays >= expiryDate) 
        {
            answer.push_back(i + 1);  // 인덱스는 1부터 시작
        }
    }
    return answer;
}
  • stringstream
더보기

stringstream은 C++에서 문자열을 입출력 스트림처럼 다룰 수 있는 클래스로 문자열을 파일, 표준 입력처럼 다루며 데이터를 읽고 쓸 수 있게 해준다.

#include <sstream>

사용하기 위해선 sstream 헤더파일을 추가해줘야 하며 주로 문자열을 공백 단위로 분리, 숫자와 문자열의 변환, 문자열 포멧팅 작업에 사용된다.


 

메서드 설명
ss << value 값을 문자열로 변환해서 스트림에 추가
ss >> variable 스트림에서 값을 읽어 변수에 저장
ss.str() 현재 스트림에 저장된 문자열 반환
ss.clear() 스트림 상태 초기화 (에러 플래그 초기화)
ss.str("text") 스트림의 내용을 새로운 문자열로 설정

 

  • stringstream은 문자열 파싱형 변환에 매우 유용
  • >> 연산자로 쉽게 데이터를 읽기
  • << 연산자로 쉽게 데이터를 쓰기
  • str()로 현재 문자열 내용 조회 가능

 

문자열에서 정수, 실수, 단어등을 쉽게 추출하거나 숫자와 문자열을 자주 변환해야 할 때, 문자열 데이터를 빠르게 파싱해야 할 때 사용된다.

(파싱: 문자열 데이터를 의미 있는 구조로 변환하는 과정 / 문자열을 분석해 필요한 정보만 추출하는 작업)

 

- 기본 사용방법

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() 
{
    string input = "A 6";
    stringstream ss(input);

    string termType;
    int duration;

    // 공백을 기준으로 데이터를 읽음
    ss >> termType >> duration;

    cout << "약관 종류: " << termType << endl;
    cout << "유효 기간: " << duration << "개월" << endl;
	//입력 A -> 출력 6개월
    return 0;
}

 

 

- 문자열 -> 숫자 변환 사용방법

#include <iostream>
#include <sstream>
using namespace std;

int main() 
{
    string numberStr = "42";
    stringstream ss(numberStr);

    int number;
    ss >> number;

    cout << "정수로 변환된 값: " << number << endl;
    //출력 정수로 변환된 값: 42
    return 0;
}

 

 

- 숫자 -> 문자열 변환 사용방법

#include <iostream>
#include <sstream>
using namespace std;

int main() 
{
    int number = 123;
    stringstream ss;

    ss << number;  // 숫자를 문자열로 변환
    string numberStr = ss.str();

    cout << "문자열로 변환된 값: " << numberStr << endl;
    //출력 문자열로 변환된 값: 123
    return 0;
}

 

- 문자열 분리 사용방법

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main() 
{
    string input = "C++ 언리얼 엔진";
    stringstream ss(input);

    string word;
    vector<string> words;

    // 공백 기준으로 문자열 나누기
    while (ss >> word) 
    {
        words.push_back(word);
    }

    // 출력
    for (const auto& w : words) 
    {
        cout << w << endl;
    }
    
//출력: C++ 
//      언리얼 
//      엔진

    return 0;
}

'C++ 메모장' 카테고리의 다른 글

반복문  (0) 2025.03.07
컨테이너 멤버 함수  (0) 2025.02.24
map, unordered_map  (0) 2025.02.21
std::find  (0) 2025.02.20
npos  (0) 2025.02.19