새로새록

[c++]4. 검색엔진 - 키워드 포함 단어 본문

소프트웨어융합/경희대 c++ 과제

[c++]4. 검색엔진 - 키워드 포함 단어

류지나 2020. 7. 14. 23:54

검색엔진을 만들려고 한다. 특정 키워드를 입력했을 때 완전히 일치하는 단어뿐만 아니라
키워드를 포함하는 단어까지 전부 출력해라. ( hint-> string의 find() 함수 사용 )


검색엔진의 데이터베이스에 있는 단어 : 사랑, 프로그래밍, 의자, 사랑의바보, 영통역,
천년의사랑, 냉장고, 객체지향

출력--------

키워드 : 사랑
검색결과 : 사랑, 사랑의바보, 천년의사랑

코드--------

#include <iostream>
#include <string>

using namespace std;

int main() {
	string lst = "사랑, 프로그래밍, 의자, 사랑의바보, 영통역, 천년의사랑, 냉장고, 객체지향";
	string key;
	string s1;
	cout << "키워드 : ";
	cin >> key;
	cout << "검색결과 : ";
	
	int i = 0;
	while (1) {
		s1.clear();
		int index = lst.find(key, i);
		int ref = index;
		if (index == string::npos)
			break;
		if (index == 0) {
			while (1) {
				if (lst.at(ref) == ',') {
					i = ref;
					break;
				}
				else {
					s1 = s1 + lst.at(ref);
					ref++;
				}
			}
		}
		else {
			while (lst.at(ref) != ' ') {
				ref--;
			}
			while (1) {
				ref++;
				if (lst.at(ref) == ',') {
					i = ref;
					break;
				}
				else
					s1 = s1 + lst.at(ref);
			}
		}
		if (lst.find(key, i) != string::npos)
			cout << s1 << ", ";
		else
			cout << s1;
	}
}

 

#include <iostream>
#include <string>
using namespace std;
int main() {
	string data = "사랑,프로그래밍,의자,사랑의바보,영통역,천년의사랑,냉장고,객체지향";
	string delimeter = ",";
	string keyword;
	string word;
	int pos = 0;
	cout << "키워드 : ";
	cin >> keyword;
	cout << "\n검색결과 : ";
	while ((pos = data.find(delimeter)) != string::npos) {
		word = data.substr(0, pos);
		if (word.find(keyword) != string::npos) {
			cout << word << " ";
		}
		data = data.substr(pos + delimeter.length());
	}
	cout << "\n";
	return 0;
}