[1204 寻找子串位置] 解题报告

题目描写叙述 Description

给出字符串a和字符串b,保证b是a的一个子串。请你输出b在a中第一次出现的位置。

输入描写叙述 Input Description

仅一行包括两个字符串a和b

输出描写叙述 Output Description

仅一行一个整数

例子输入 Sample Input

abcd bc

例子输出 Sample Output

2

数据范围及提示 Data Size & Hint

字符串的长度均不超过100

Pascal用户请注意:两个字符串之间可能包括多个空格



#include <stdio.h>

// 寻找子串位置
inline int findSubStrLocation(int *str,int *subStr){
    int *p = str,*q = NULL,*p_move = NULL;  // p指向主串,p_temp为p的滑动指针,q指向子串
    while (*p != '') {
        q = subStr;
        p_move = p;
        while (*q != '') {
            // 滑动匹配,滑动过程中出现不匹配直接跳出循环,假设一直匹配到最后一个字符则返回位置
            if (*p_move != *q) {
                break;
            }else{
                q++;
                p_move++;
            }
            
            if (*q == '') {
                return (int)(p - str + 1);
            }
        }
        p++;
        q = subStr;
    }
    return NULL;
}

int main(){

    int str[100],subStr[100],i = 0;
    char temp = NULL;
    
    while ((temp = getchar()) != ' ') {
        str[i++] = temp;
    }
    str[i] = '';
    i = 0;
    
    while ((temp = getchar()) != '
') {
        if (temp != ' ') {      // 中间多个空格处理
            subStr[i++] = temp;
        }
    }
    subStr[i] = '';
    
    printf("%d
",findSubStrLocation(str,subStr));
    
    return 0;
}






原文地址:https://www.cnblogs.com/mfrbuaa/p/5282859.html