๐Ÿ“ Coding Test Study/C++

[10์ฃผ ์™„์„ฑ C++ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ] ๋ฌธ์ž์—ด ํ•„์ˆ˜๊ฐœ๋… - split(), substr(), erase()

ibelieveinme 2023. 8. 5. 21:25
728x90

* split(): ํŠน์ • ๋ฌธ์ž์—ด์„ ๊ธฐ์ค€์œผ๋กœ ์ชผ๊ฐœ๋Š” ํ•จ์ˆ˜.

              C++ ์—์„  ์ง€์›ํ•˜์ง€ ์•Š์•„์„œ ์ง์ ‘ ๊ตฌํ˜„ํ•ด์•ผ ํ•จ.

 

* ์‹œ๊ฐ„๋ณต์žก๋„: O(n)

 

* ๋„์–ด์“ฐ๊ธฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด์„ ์ชผ๊ฐœ๋Š” ์˜ˆ์‹œ ์ฝ”๋“œ. ์•”๊ธฐ โ˜…โ˜…โ˜…โ˜…โ˜…

#include <iostream>
#include <string>
#include <vector>
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) {
		token = input.substr(0, pos); // "์•ˆ๋…•ํ•˜์„ธ์š”"
		ret.push_back(token);
		input.erase(0, pos + delimiter.length()); // "์•ˆ๋…•ํ•˜์„ธ์š” "
	}
	ret.push_back(input);
	return ret;
}

int main() {
	string s = "์•ˆ๋…•ํ•˜์„ธ์š” ๋นต์ด๋นต์ด์”จ, ๋งˆ๋‹ˆ ๋ฅ์ง€์š”?", d = " ";
	vector<string> a = split(s, d);

	for (string b : a) cout << b << "\n";

	return 0;
}

 

find(์ฐพ๋Š” ๋ฌธ์ž์—ด): ๋ฌธ์ž์—ด์—์„œ ์ฐพ๋Š” ๋ฌธ์ž์—ด์˜ ์œ„์น˜๋ฅผ returnํ•จ.

string::npos: find ํ•จ์ˆ˜์—์„œ ์ฐพ๋Š” ๋ฌธ์ž์—ด์ด ์—†๋Š” ๊ฒฝ์šฐ string::npos๋ฅผ ๋ฐ˜ํ™˜ํ•จ

substr[์‹œ์ž‘์œ„์น˜, ๋ถ€๋ถ„ ๋ฌธ์ž์—ด ๊ธธ์ด): ๋ฌธ์ž์—ด์˜ ์ผ๋ถ€๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜. substr(0, 4) ์ด๋ฉด 0,1,2,3 ๊ฐ’์„ return.

erase[์‹œ์ž‘์œ„์น˜, ๊ธธ์ด): ๋ฒกํ„ฐ์˜ ํŠน์ • ์›์†Œ๋ฅผ ์ง€์šฐ๋Š” ํ•จ์ˆ˜. erase(0, 5) ์ด๋ฉด 0,1,2,3,4 ๊ฐ’์„ ์ง€์›€.

for(ํƒ€์ž… ์ž„์‹œ๋ณ€์ˆ˜๋ช… : ํƒ€์ž…์„ ๋‹ด์€ ์ปจํ…Œ์ด๋„ˆ): ๋ฒ”์œ„๊ธฐ๋ฐ˜ for ๋ฃจํ”„

 

728x90