Bradbury 2020. 9. 8. 15:42
728x90

1. 문자열 대소문자 변환(헤더 algorithm)

- ::tolower나 ::toupper를 사용(::없으면 프로그래머스 바로 오류남)

string word = "HELLO";
transform(word.begin(), word.end(), word.begin(), ::tolower);
cout << word << endl; // hello

// 하나씩도 가능
for (int i = 0; i < word.size(); i++) {
	word[i] = ::toupper(word[i]);
}
cout << word << endl; // HELLLO

 

2. 문자열 전부 순회하며 특정 문자열 찾기

- find로 찾지 못할 경우 -1이 아닌 srd::string::npos이다

string line = "hello my namloe is lo go ewew difk ck";
string word = "lo";
int pos = line.find(word);
while (pos != std::string::npos){
	cout << line.substr(pos, word.size()) << endl;
	pos = line.find(word, pos + word.size());
}

 

3. 알파벳을 제외한 모든 특수 문자 공백으로 변환(algorithm 헤더)

- 토큰화할때 유용하게 사용

- replace_if

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

// 알파벳이 아닌 경우
bool wordChange(char c) {
	return c == '\'' || !isalpha(c);
}

int main() {
	string line = "h{el@@lo \tmy \"namlo<<e is lo go e{we>>>w difk ck";

	// 특수 문자들도 분리하기 위해 알파벳이 아닐시 싹다 공백으로 변환
	replace_if(line.begin(), line.end(), wordChange, ' ');

	cout << line << endl;
	return 0;
}
728x90