반응형

문자열을 일정 길이로 자르는 C++ 코드를 작성해보았습니다.



2021. 1. 12 - 최초작성



#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> block_string(std::string input, int want_block_length)
{
std::vector<std::string> ret;
int length;


std::string str = input;

while (str.length() > want_block_length)
{
std::string msg = str.substr(0, want_block_length);
std::string rest = str.substr(want_block_length);

// std::cout << msg << " " << rest << std::endl;
ret.push_back(msg);

str = rest;
}

// std::cout << str << std::endl;
ret.push_back(str);

return ret;
}

int main()
{
std::string text = "1234567890";


    std::cout << text << std::endl;

std::vector<std::string> result1;
result1 = block_string(text, 2);  // 2문자씩 자르기

for(int i=0; i<result1.size(); i++)
std::cout << result1[i] <<" ";
std::cout << std::endl;


std::vector<std::string> result2;
result2 = block_string(text, 3);  // 3문자씩 자르기

for(int i=0; i<result2.size(); i++)
std::cout << result2[i] << " ";
std::cout << std::endl;
}



1234567890

12 34 56 78 90 

123 456 789 0 



반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts