본문 바로가기
연습장

Split Strings

by anothel 2021. 10. 19.

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').

Examples:

solution("abc") // should return {"ab", "c_"}
solution("abcdef") // should return {"ab", "cd", "ef"}

 

Solution

#include <string>
#include <vector>

std::vector<std::string> solution(const std::string &s) {
  std::vector<std::string> result;
  std::string sTmp;
  for (auto x : s) {
    sTmp += x;
    if (sTmp.size() == 2) {
      result.push_back(sTmp);
      sTmp.clear();
    }
  }

  if (sTmp.empty() == false) {
    sTmp += "_";
    result.push_back(sTmp);
  }

  return result;
}

 

후기

남의 코드를 봤을 때, 아주아주 다양한 방법으로 코드를 풀어갔다. 하지만 1등 코드는 내가 짜 놓은 코드와 비슷한 느낌의 코드가 1등이었고 대부분 이렇게 풀었더라. 하긴 읽기 좋은 코드가 좋은 코드이다. 이 책이 제목인 책 얼른 읽어봐야겠다.

 

(url: https://www.codewars.com/kata/515de9ae9dcfc28eb6000001)

 

728x90

'연습장' 카테고리의 다른 글

Sum of Digits / Digital Root  (0) 2021.10.19
Find the odd int  (0) 2021.10.19
Perimeter of squares in a rectangle  (0) 2021.10.19
곱셈 - 2588  (0) 2021.10.19
A/B - 2 - 15792  (0) 2021.10.19