프로그래머스 모스부호 (1) [c++] stringstream 사용법

Roh·2023년 2월 1일
0
post-thumbnail

c++ stringstream의 기본적인 사용법은 아래와 같다. string 타입 변수 s가 "<<" 연산자를 통해 stringstream 타입 변수 ss에 저장되고 ">>" 연산자를 이용해 ' '(space, white space, 공백) 단위로 잘려서 나온다.

#include <sstream>
#include <string>
#include <iostream>

using namespace std;

int main() {

	string s = "hello my velog";
	stringstream ss;
	
	string stringTmp = "";

	ss << s;
	ss >> stringTmp;
	cout << stringTmp << endl;

	// console : hello

	ss >> stringTmp;
	cout << stringTmp << endl;

	// console : my

	ss >> stringTmp;

	cout << stringTmp << endl;

	// console : velog
	return 0;

}

이제 기본적인 stringstream의 사용법을 알았으니 바로 문제를 풀어보자.

문자 ".-"는 morse의 첫 번째 index이고 문자로는 a이다.
우리는 아래와 같은 변환 과정을 통해 정답을 구해볼 것이다.
모스부호 ➜ index ➜ 문자

     strTmp 와 morse[i](모스부호)가 같으면 
     if(strTmp == morse[i])
     구한 인덱스 i 를 문자로 바꾼다.
     answer += (char)(i + 'a');
#include <string>
#include <vector>
#include <sstream>

using namespace std;

string morse[] = { ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",
           ".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",
           ".--","-..-","-.--","--.." };

string solution(string letter) {
    string answer = "";
    string strTmp = "";
    stringstream ss;
    ss << letter;

    while (ss >> strTmp)
    {
        for (int i = 0; i < 26; i++) {
            if (strTmp == morse[i]) {
                answer += (char)(i + 'a');
            }
        }
    }

    return answer;
}
profile
Better than doing nothing

0개의 댓글