본문 바로가기
  • " 집요함 "
  • " 집요함 "
  • " 집요함 "
알고리즘/코딩 & 알고리즘 공부

[C++] find, substr, erase, insert

by joen00 2021. 7. 23.

 

find

문자열에서 원하는 문자열을 찾는 것이다.

 

시간 복잡도는 O(n)의 속도

 

find(대상, 위치)

#include <iostream>
#include <string>
#include <cstring>
using namespace std;


int main() {

	string arr = "ZXCVASDFASDFAS";
	int a = arr.find("ASDF");
	cout << a << endl;
	
	int b = arr.find("ASDF", a + 1);
	cout << b << endl;
	
	int c = arr.find('Z');
	cout << c << endl;

	int d = arr.find("as");
	cout << d << endl;

	return 0;
}
더보기

 

결과

 

4
8
0
-1

 

a의 경우 해당 위치 index

b의 경우 a 다음 해당 위치 index

c의 경우 문자 하나의 위치 index

d의 경우 없는 문자열의 값

 

 

substr

문자열에서 원하는 문자열만 자르기

 

substr(4번 인덱스, 2개의 값) 

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main() {

	string s = "ASDF[KFC]ASDF";
	int a = s.find("[");
	int b = s.find("]");
	string target = s.substr(a + 1, b - a - 1);
	cout << target;

	return 0;
}
더보기

결과

 

KFC

 

 

erase

원하는 위치에서 그 size 만큼 지우기

 

erase(위치, size)

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main() {

	string s = "ASDF[KFC]ASDF";
	s.erase(4,5);
	cout << s;

	return 0;
}
더보기

결과

 

ASDFASDF

 

 

insert

원하는 위치에 문자열 넣기

 

insert(위치, 대상)

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main() {

	string s = "ASDF[KFC]ASDF";
	s.insert(4, "asdf");
	cout << s;

	return 0;
}
더보기

결과

 

ASDFasdf[KFC]ASDF

 

728x90

댓글