数据结构示例之查找子字符串的起始位置

来源:互联网 发布:51单片机控制继电器 编辑:程序博客网 时间:2024/06/06 04:00

以下为“查找子字符串的起始位置”的简单示例

1. 用c语言实现的版本

#include <stdio.h>#include <string.h>/* 查找子字符串的起始位置 */int nfind(char *strSrc, char *strFind){int  i = 0, j = -1;int  lastSrcPos = strlen(strSrc) - 1; //原始字符串的最大下标值int  lastFindPos = strlen(strFind) - 1; //要搜索的字符串的最大下标值int   startSrcMatch = 0, endSrcMatch = lastFindPos; //匹配成功的子字符串的起始下标和结束下标值for ( ; endSrcMatch <= lastSrcPos; ++endSrcMatch, ++startSrcMatch){if (strSrc[endSrcMatch] == strFind[lastFindPos]) // 子字符串结束下标处的字符 == 要查找的字符串中最后一个字符 {for (j = 0, i = startSrcMatch; j<lastFindPos && strSrc[i] == strFind[j]; ++j, ++i){}}if (j == lastFindPos){return (startSrcMatch + 1); /* 成功 */}}/*printf("%d %d %d",lasts,lastp,start); *//* 失败 */return  -1;}void main(){char strSrc[] = "Sit please";char strFind[] = "please";/* 查找子字符串的起始位置 */int po = nfind(strSrc, strFind);printf("原始字符串:%s\n", strSrc);printf("要查找的字符串:%s\n", strSrc);printf("匹配子字符串的起始位置:%d\n", po);}

运行结果为:


0 0
原创粉丝点击