Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 월곡역 학원
- c++ 조합
- C++ 문자열
- 백준 한국이 그리울 땐 서버에 접속하지
- 고정 소수점
- 월곡중 학원
- 성북구 학원
- 백준 14246번 K보다 큰 구간
- 백준 10709
- C# 병합정렬
- 백준 2309번 일곱 난쟁이
- 백준 K보다 큰 구간
- DFS
- 관리형 학원
- 운영체제
- C++ 9996
- 백준 패션왕 신해빈
- OS
- 백준 1049번
- 백준 14246번
- c++ split
- 서울사대부고 학원
- 백준 dfs
- 월곡동 학원추천
- 백준 토마토
- 상월곡역 학원
- 상월곡동 학원
- 월곡중학교 학원추천
- 백준 1049번 기타줄
- 백준 9375번 패션왕 신해빈
Archives
- Today
- Total
키베이루's diary
[C++] Split 본문
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] << ' ';
}
}
'알고리즘 > 문자열' 카테고리의 다른 글
[C++] 백준 9375번 패션왕 신해빈 (0) | 2022.12.29 |
---|---|
[C++] Map (0) | 2022.12.29 |
[C++] 백준 9996번 한국이 그리울 땐 서버에 접속하지 (0) | 2022.12.28 |
[C++] String(문자열) (0) | 2022.12.28 |
Comments