반응형

C언어 문자열이 다른 문자열 포함 여부 판단

 

 

문자열 str2이 문자열 str1이 있는 경우 해당문자열의 시작점 반환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* Find first position of str1 in str2, or return false (-1). */
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
 
// Find first position of str1 in str2, or return -1
int findString(const char str2[], const char str1[]) {
    int i;    
    bool ok;
 
    for (i = 0; str2[i] != '\0' && !ok; i++) {
        ok = true;
        for (int j = 0; str1[j] != '\0' && ok; j++) {            
            if (str2[i+j] != str1[j]) ok = false;
        }
    }   
    return ok ? i - 1 : -1;
}
 
void testFindString() {
    printf("'cat'     'cat'  %2d\n", findString("cat","cat"));
    printf("'cat'     'c'    %2d\n", findString("cat","c"));
    printf("'cat'     'a'    %2d\n", findString("cat","a"));
    printf("'cat'     't'    %2d\n", findString("cat","t"));
    printf("'cat'     'b'    %2d\n", findString("cat","b"));
    printf("'apple'   'pe'   %2d\n", findString("apple","pe"));
    printf("'apple'   'ple'  %2d\n", findString("apple","ple"));
    printf("'banana'  'nab'  %2d\n", findString("banana","nab"));
 
}
 
int main() {
    testFindString();
}
cs

 

 

반응형