키베이루 2022. 12. 26. 13:46

Split은 문자열을 특정 문자열을 기준으로 쪼개어서 배열화 시키는 함수의 의미로 사용된다.

C++에서는 split() 함수를 지원하지 않기때문에 직접 구현해야한다.

 

#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;

vector<string> split(string input, string delimiter) {
	vector<string> ret;
	long long pos = 0;
	string token = "";
	while ((pos = input.find(delimiter)) != string::npos) { // input문자열에서 delimeter을 찾는다
		// 못찾는다면 이 루프는 반복된다.
		token = input.substr(0, pos);
		// substr (시작위치, 길이) = 시작위치에서 길이만큼
		// 문자열을 취득하여 token에 저장한다.
		ret.push_back(token);
		// token에 저장된 문자열을 ret에 저장한다.
		input.erase(0, pos + delimiter.length());
		//erase (시작위치, 길이) = 시작위치에서 길이만큼
		// 문자열을 삭제한다.
	}
	ret.push_back(input);
	return ret;
}
int main() {
	string s = "Hello World Bye world.";
	string d = " ";
	vector<string> a = split(s, d); // s라는 문자열을 d를 기준으로 구분한다.
	for (string b : a) {
		cout << b << endl;
	}
}

 

이를 세분화하면

while ((pos = input.find(delimiter)) != string::npos)

input문자열에서 delimiter를 찾는 구문으로 찾지 못한다면 루프는 반복된다.

 

string token = "";
token = input.substr(0, pos);

문자열.substr(시작위치, 길이) : 시작위치에서 길이만큼 문자열을 잘라서 token에 저장하는 기능

 

ret.push_back(token);

input.erase(0, pos + delimiter.length());

token문자열을 ret문자열에 저장한다.

문자열.erase(시작위치, 길이) : 문자열의 시작위치에서 길이만큼 문자열을 삭제한다.

 

범위기반 for문

vector<int> a;
for (string b : a) {
	cout << b << endl;
}

vector a내에 있는 요소인 string 타입의 요소를 b에 할당하여 출력하는 코드

for(int i=0;i<a.size();i++){
	cout << a[i] << endl;
}

이 코드와 같은 의미이다. (a의 길이만큼 반복문을 돌면서 a의 인자를 출력한다)

예제 

https://www.acmicpc.net/problem/10808

 

10808번: 알파벳 개수

단어에 포함되어 있는 a의 개수, b의 개수, …, z의 개수를 공백으로 구분해서 출력한다.

www.acmicpc.net

 

#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;


int cnt[26];
int main() {
	string str;
	cin >> str;
	for (char a : str) { // str의 요소를 반복하여 변수 a에 요소의 값을 할당.
		cnt[a - 'a']++;
	}
	
	for (int i = 0; i < 26; i++) {
		cout << cnt[i] << ' ';
	}
}