More actions
소감
어쩌다가 이렇게 길어지게 됐는지 모르겠다. 여튼 처음 문제를 접했을 때 연필을 끄적거리지 않았어서 후회가 생긴다. 연필을 잡지 않으면 시간이 배로 드는것 같다. 앞으로 실수하지 않게 데블스캠프때 배웠듯이, 건축에 있어서 설계를 작성하는것은 중요한 것 처럼 프로그래밍에 있어서도 구상과 설계는 매우 중요하다고 느낀다.
알고리즘
그냥 알고리즘을 생각했다. 어떻게 보면 복잡한 것 같기도 하다.ㅡㅠ His teaching method is very good. 이번 프로그래밍의 알고리즘. 단어의 시작을 중점으로 한다.(나는 문자열 이라기 보다는 단어 검색 중심으로 짠것같다.) 즉, H, t, m, i, v, g가 기점이 될 수 있다. 문장 속의 단어의 첫 글자와, 찾아볼 단어의 첫글자의 동일한가 부터 시작한다. 만약에 Hot이라는 단어를 저 문장에서 찾았을때, 먼저 H로 시작하는 단어가 있기 때문에 His와 비교를 당하게 된다. 다음은 o와 i.. 다르기 때문에 found 이 0이 되어서 찾지 못했음을 알린다. 만약에 첫 글자 부터 동일하지 않다면 비교도 하지 않고도 찾지못함을 알린다.
소스
#include <stdio.h>
void exist_word(char x[40], int exist_str[10]); //x[i]에 문자열의 유무
int compare_str(char x[40], char search_str[15], int exist_str[10]); // 문자열 비교
int word_num = 1, search_str_num = 0;
int found = 0; int temp = 0;
void main()
{
char x[40] = "His teaching method is very good.";
char search_str[15];
int exist_str[10]; // exist_str[i]에는 x문자열중 i번째 문자열이 몇번째 문자에 나오나
FILE *fp;
fp = fopen("result.out", "w");
while(1){
word_num = 1; search_str_num = 0; found = 0; temp = 0;
printf("끝내려면 ""EE""입력\n"); //출력.
printf("자료 -> %s", x);
printf("\n찾을 문자열 -> ");
scanf("%s", search_str);
fprintf(fp,"자료 -> %s", x); //result.out에 저장.
fprintf(fp, "\n찾을 문자열 -> ");
fprintf(fp, "%s", search_str);
if(search_str[0] == 'E' && search_str[1] == 'E')
break;
exist_word(x, exist_str);
found = compare_str(x, search_str, exist_str);
switch(found){
case 1:
fprintf(fp, "\nfirst found -> %d\n\n", exist_str[word_num]+1);
break;
case 0:
fprintf(fp, "\nNot found!\n\n");
break;
}
}
fclose(fp);
}
void exist_word(char x[40], int exist_str[10])
{
int num = 2, x_n = 0;
exist_str[1] = 0;
while(x[x_n])
{
if(x[x_n] == ' ')
{
exist_str[num] = x_n + 1; //빈칸 다음에 문자열이 나온다고 가정.
++num;
}
++x_n;
}
}
int compare_str(char x[40], char search_str[15], int exist_str[10])
{
if(x[exist_str[word_num]] != search_str[search_str_num])
{
++word_num;
if(exist_str[word_num] >= 0)
compare_str(x, search_str, exist_str);
}else{
temp = exist_str[word_num];
while(search_str[search_str_num])
{
if(x[temp] == search_str[search_str_num]){
found = 1;
++temp;
++search_str_num;
}else{
found = 0;
break;
}
}
}
return found;
}
C++로 문자 검색.
//cpp1.cpp
#include <iostream>
#include "class.h"
using namespace std;
void main()
{
Search_ch c;
c.input();
c.search();
c.print();
}
//cpp2.cpp
#include <iostream>
#include "class.h"
using namespace std;
void Search_ch::input()
{
cin>>str;
cin>>ch;
}
int Search_ch::search()
{
int i, str_len, k;
str_len = strlen(str);
for(i = 0; i <= str_len-1; i++)
{
if(str[i] == ch)
{
k = i;
break;
}else{
k = 0;
}
}
return k;
}
void Search_ch::print()
{
int found_num = search();
if(found_num == 0){
cout << "Not Found!!";
}else if(0 < found_num && found_num < strlen(str)){
cout << "Found!! >>>" <<found_num+1;
}
}
//class.h
class Search_ch
{
private:
public:
char str[20];
char ch;
void input();
int search();
void print();
};