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
- 16202
- 사이클 없는 그래프
- 줄어드는수
- hcpc
- 투포인터 #백준 #boj #20922 #22862
- C++
- backtracking #codetree #디버깅 #삼성코테
- 진법변환 #2to10 #10to2 #이진법 #십진법 #변환 #bitset #c++
- 레드아보
- c++ #입출력 #속도 #ios #sync_with_stdio #cin #cout #tie
- 30870
- 20117
- graph #최단경로
- 3D #Reconstruction #computer #vision #volume #metric #tsdf #kinect #fusion
- 백준
- 백준 #다익스트라 #dijkstra #9370 #c++
- N번째큰수
- graph
- 쌤쌤쌤
- 3343
- 22869
- LIS #가장긴증가하는부분수열 #
- 1174
- 코딩
- 이분탐색 #dp #11053
- 호반우 상인
- BOJ
- c++ #boj #
- boj #백준
- 최소 #공배수 #최대 #공약수 #유클리드 #호제법 #lcm #gcd #c++ #boj #3343 #백준 #장미
Archives
- Today
- Total
hyunjin
[C++][BOJ/알파벳찾기/10809] string의 substring 찾기 find 함수, string :: npos 본문
알고리즘 연습/백준
[C++][BOJ/알파벳찾기/10809] string의 substring 찾기 find 함수, string :: npos
_h.j 2021. 2. 15. 23:27728x90
백준 10809 바로가기
문자열을 입력받고 각 문자에 각 알파벳에 대해 문자열에서 처음 나오는 위치를 출력하는 문제다.
위치 찾는 방법을 find 활용해서 풀어보자.
소스코드1
#include <bits/stdc++.h>
using namespace std;
int main(){
string w;
cin>>w;
// 기본 풀이
int a[26];
memset(a,-1,sizeof(a));
for(int i = -1; w[++i] ;)
if(a[w[i]-'a'] < 0)
a[w[i]-'a'] = i;
for(auto e : a) cout<<e<<" ";
}
소스코드2
#include <bits/stdc++.h>
using namespace std;
int main(){
string w;
cin>>w;
// find 활용해서 바로 가능
for(char c = 'a'; c<='z';c++) cout<<int(w.find(c))<<" ";
return 0;
}
▶ str.find(...)
원형
size_t find (const string& str, size_t index = 0) const;
설명
string에서 특정 substring을 찾는다. 매개 변수로 들어온 문자열과 내 문자열 중 일치하는 것이 있는 지 확인
5개 오버로딩 되어있다.
원형에서 index는 어느 위치에서 부터 찾을지
리턴값
일치하는 문자열이 있다면 문자열의 첫 번째 위치 반환 (0 부터 시작)
없는 경우 string::npos 반환 ( -1 반환이 아님 주의 , constant로 선언된 경우 -1로 리턴된다하고.. 아무튼 사용시 주의 )
가장 자주 쓰이는 형태
s.find("substring");
일치 문자열 없는 경우 사용법
if( s.find("substr") == string::npos ){
cout<< -1 <<endl;
}
이렇게 쓰는 것이 더 안전. 백준 문제에선 어찌 어찌 통과되었지만 주의하자...
참고
728x90
'알고리즘 연습 > 백준' 카테고리의 다른 글
[C++][BOJ 나머지(10430)] 유클리드 호제법 (0) | 2021.02.16 |
---|---|
[C++][BOJ- 10808/10820/1165/1166] islower, isupper,isdigit,isalpha , <string ,int,char>간 변환 (0) | 2021.02.16 |
[C++][BOJ /9012/괄호] 여러 풀이 - 배열, 스택, int , scanf(%*d) (0) | 2021.02.11 |
[C++][BOJ-2225(합분해)] (0) | 2021.02.10 |
[C++][BOJ-정렬 문제들(2751 11650 11651 10814 10989 11652)] stable_sort, vector pair 정렬, 메모리 계산, map,int 범위 , (0) | 2021.02.10 |