그럴듯한 개발 블로그
Published 2023. 5. 29. 01:20
cpp split <language>/c++
반응형

문자열 알고리즘 문제 나오면 매번 구현하다 빡쳐서 하나 만듬

#include <string>
#include <vector>
using namespace std;

vector<string>	ft_split(string s, char sep) // 구분자 하나짜리
{
	vector<string>	res;
	int	start_idx = 0;

	for (int i = 0; i < s.size(); i++)
	{
		if (s[i] == sep)
		{
			if (i > start_idx)
				res.push_back(s.substr(start_idx, i - start_idx));
			start_idx = i + 1;
		}
	}
		if (start_idx < s.size())
			res.push_back(s.substr(start_idx, s.size() - start_idx));
	return (res);
}

++더 편한게 있었다.

stringstream 쓰세요~

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

std::vector<std::string> splitString(const std::string& str, char delimiter) {
	std::vector<std::string> tokens;
	std::stringstream ss(str); // stringstream ss에 str을 넣어준다
	std::string token;

	while (std::getline(ss, token, delimiter)) // 공백 말고 다른 문자로 나누고 싶을 때
		tokens.push_back(token);

	return tokens;
}

int main() {
	std::string sentence = "Hello, world! How are you?";
	char delimiter = ' ';

	std::vector<std::string> words = splitString(sentence, delimiter);

	for (const auto& word : words) {
		std::cout << word << std::endl;
	}

	return 0;
}

 

반응형

'<language> > c++' 카테고리의 다른 글

c++ class 상속, 가상함수 테이블, 추상클래스  (0) 2023.08.07
c++ 레퍼런스(참조자)  (8) 2023.07.06
c++ 동적할당  (0) 2023.07.06
cpp 파일 컨트롤(ifstream ofstream)  (0) 2023.07.05
STL 해시  (0) 2023.04.06
profile

그럴듯한 개발 블로그

@donghyk2

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!