개요
알고리즘 문제를 풀다 보면 문자열 내 특정 부분 문자열이 시작하는 위치를 찾아야 하는 경우가 있습니다.
이때, 특정 부분 문자열이 여러 번 나올 경우 시작하는 위치들을 아래와 같은 코드를 통해 찾을 수 있습니다.
코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(0);
cin.tie(0);
string inputString, inputSubString;
cin >> inputString >> inputSubString;
size_t idx = inputString.find(inputSubString);
vector<int> beginningIdxesOfSubstring;
while (idx != string::npos)
{
// 부분문자열이 시작하는 위치들을 벡터에 추가
beginningIdxesOfSubstring.push_back(idx);
idx = inputString.find(inputSubString, idx + 1);
}
cout << "부분문자열이 시작하는 위치들: ";
for (int idx : beginningIdxesOfSubstring)
{
cout << idx << " ";
}
cout << "\n";
return 0;
}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
string inputString, inputSubString; | |
cin >> inputString >> inputSubString; | |
size_t idx = inputString.find(inputSubString); | |
vector<int> beginningIdxesOfSubstring; | |
while (idx != string::npos) | |
{ | |
// 부분문자열이 시작하는 위치들을 벡터에 추가 | |
beginningIdxesOfSubstring.push_back(idx); | |
idx = inputString.find(inputSubString, idx + 1); | |
} | |
cout << "부분문자열이 시작하는 위치들: "; | |
for (int idx : beginningIdxesOfSubstring) | |
{ | |
cout << idx << " "; | |
} | |
cout << "\n"; | |
return 0; | |
} |
결과

반응형
'[DEV] 기록' 카테고리의 다른 글
[javascript] 클립보드로 복사하는 방법 (0) | 2021.04.25 |
---|---|
[SpringBoot] 세션이 만료될 때 세션 값 가져오는 방법 (0) | 2021.04.24 |
[크롤링] 경향신문 크롤링 (6) | 2021.04.12 |
[Spring] Maven 정리 (0) | 2021.03.03 |
Intellij IDEA(인텔리제이) 단축키 정리 (1) | 2021.03.02 |