Skip to content

Instantly share code, notes, and snippets.

@prodeveloper0
Created February 18, 2016 16:56
Show Gist options
  • Select an option

  • Save prodeveloper0/6a9ec802ca27a44a7d3a to your computer and use it in GitHub Desktop.

Select an option

Save prodeveloper0/6a9ec802ca27a44a7d3a to your computer and use it in GitHub Desktop.
cmd.exe 명령 분할기 구현
#include <iostream>
#include <string>
#include <vector>
//
// 문자열을 구 또는 단어 단위로 분리하는 함수.
//
// str: 분리할 문자열.
// div: 분리된 문자열의 벡터.
//
// 반환값: true/false. 문자열이 성공적으로 분리 되었다면, true 반환.
//
bool divstr(const std::string &str, std::vector<std::string> &div)
{
std::string::size_type slen = str.length(); // 명령줄 길이.
std::string::size_type start_pos = 0; // 명령줄에서 뽑아낼 구 또는 단어의 첫 인덱스.
for(std::string::size_type curr_pos = 0;curr_pos <= str.length();++curr_pos)
{
if(str[curr_pos] == ' ' || str[curr_pos] == NULL) // 문자열의 현재 위치가 띄어쓰기나 문자열의 끝일 경우.
{
// 띄어쓰기나 NULL의 시작 위치와 현재 위치가 +1 이상 차이나는 경우,
// 띄어쓰기나 NULL의 시작 위치로부터 현재 위치까지 문자열을 잘라서 벡터에 추가.
if((curr_pos - start_pos) >= 1)
div.push_back(str.substr(start_pos, curr_pos - start_pos));
// 현재의 위치가 띄어쓰기나 NULL이기 때문에 의미 없는 위치다.
// 시작 위치에 현재 위치에서 +1 증가된 값을 넣어주자.
start_pos = curr_pos + 1;
}
else if(str[curr_pos] == '\"') // 문자열의 현재 위치가 인용 부호일 경우.
{
// 현재 위치에 있는 인용 부호부터 다음에올 인용 부호를 찾는다.
std::string::size_type next_quotation_pos = str.find('\"', curr_pos + 1);
// 다음 인용 부호 위치가 std::string::npos라면,
// 인용부호가 닫히지 않았으므로 불 완전한 문자열이다.
// false를 리턴하고 함수 종료.
if(next_quotation_pos == std::string::npos)
return false;
// 현재 위치에 있는 인용 부호부터 다음에올 인용 부호까지 문자열을 잘라서 벡터에 추가.
// 만약 처음부터 '"'가 나왔다면, '"'를 제거 하고 넣고,
// 아니라면 '"'는 예외케이스로서만 사용 한다.
if(curr_pos - start_pos <= 0)
div.push_back(str.substr(start_pos + 1, next_quotation_pos - start_pos - 1));
else
div.push_back(str.substr(start_pos, next_quotation_pos - start_pos + 1));
// 다음에올 인용 부호 역시 다음에는 띄어쓰기나 NULL이므로 의미 없는 위치다.
// 현재 위치와 시작 위치를 다음에올 인용 부호 위치에서 +2 증가 시킨다.
start_pos = next_quotation_pos + 2;
curr_pos = next_quotation_pos + 2;
}
}
// 만약 모든게 완료 되었다면, true를 리턴하고 함수 종료.
return true;
}
int main(int argc, char **argv)
{
while(true)
{
std::string cmd;
std::vector<std::string> cmdlist;
std::cout << ">> ";
std::getline(std::cin, cmd);
if(divstr(cmd, cmdlist))
for(auto &s : cmdlist)
std::cout << s << std::endl;
else
std::cout << "String is not completed." << std::endl;
std::cout << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment