/**
* Copyright (c) 2001,2002 Yoon, Hyunho <hhyoon@kldp.org>
* http://mooo.org
* ----------------------------------------------------------------------
*
* LICENSE
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
* strfind()
*
* char *strfind(char *s, char *t)
* 1. 두개의 문자열을 매개변수로 받는다.
* 2. 첫번째 문자열은 대상이 되는 문자열,
* 두번째 문자열은 찾고자 하는 문자열이다.
* 3. 첫번째 문자열 내에서 두번째 문자열을 찾으면 ..
* 그 주소를 반환하고, 없으면 NULL을 반환한다.
*/
#include <stdio.h>
char *strfind(char *s, char *t);
int main()
{ char str= "Welcome to Bitcamp!";
char target= "tca"; // 찾을 문자열
char *location; // 반환되어질 문자열의 주소를 저장할 변수
printf("%s <= %s\n", str, target);
printf(" 1 2 3 4\n");
printf("1234567890123456789012345678901234567890\n\n");
location = strfind(str, target);
if (location)
printf("The index of \"%s\" is %d\n", target, (location - str + 1));
else
printf("There is no \"%s\" in \"%s\".\n", target, str);
return 0;
}char *strfind(char *s, char *t)
{ int i, j;
int len_str, len_target;
// 두 문자열의 길이를 구한다.
for (len_str = 0; s[len_str] != '\0'; len_str++) ;
for (len_target = 0; t[len_targe!= '\0'; len_target++) ;
// 원본 문자열의 길이에서 찾을 문자열의 길이를 뺀 만큼만 루프를 돌면 된다.
for (i = 0; i < len_str - len_target; i++) {
// 찾을 문자열의 길이만큼 for문을 돈다.
for ( j = 0; j < len_target; j++) {
if (s[i + j] != t[j]) // 위치의 문자들이 같지 않다면 loop를 빠진다.
break;
}
// 만약 j가 len_target과 같다면, 즉 앞의 for문이 중간에
// break가 되지 않고 끝까지 다 돌았다면 문자열을 찾은 것이다.
if (j == len_target)
return (s + i); // 찾은 문자열의 시작 주소를 리턴한다.
}
// 문자열을 못찾았다면 NULL을 반환한다.
return (NULL);
}