알고리즘/C++

[ C++ ] String 에서 split 사용하기

주옹스 2020. 12. 11. 00:17

-  C++ Split 사용방법

 

 

헤더 : #include<sstream> 

 

stringstream ss( "split할 string이름" );  

getline( ss,"split한 결과값 저장할 변수명"," split에서 사용할 구분자");

 

 

 

 

 

 

 

 

-  string 에서 int로 변환 

 

헤더 : #include<string> 

 

stoi("int로 변환할 string변수명")

 

 

 

 

 

 

 

 

[ 사용 예제 ]

 

"프로그래머스_최댓값과 최솟값"

문제 링크: programmers.co.kr/learn/courses/30/lessons/12939

 

코딩테스트 연습 - 최댓값과 최솟값

문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 (최소값) (최대값)형태의 문자열을 반환하는 함수, solution을 완성하세요. 예를

programmers.co.kr

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
 
using namespace std;
 
vector<int>Number;
 
string solution(string s) {
    string answer = "";
    string splitstring;
    stringstream ss(s);
    
    while(getline(ss,splitstring,' ')){
      
        int num = stoi(splitstring);
        Number.push_back(num);
    }
    
    int mmin = *min_element(Number.begin(),Number.end());
    int mmax = *max_element(Number.begin(),Number.end());
    
    answer=to_string(mmin)+' '+to_string(mmax);
    return answer;
}