|
/*在一个字串 _bstr 中查找一子串 a_str,若存在则返回子串在主串中的起始位置,不存在则返回-1 ,可直接编译。
complied by VC6
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SLEN 16
/* 15:12 2020/2/3,This file is about string,you will input a string and a son
string,throught the function strstr ,if string named "a_str" is included by
string that is named "_bstr",you will get a result and end this function!*/
char * s_gets(char *st, int n);
int _FindChar(char *_bstr, char *a_str);
int main()
{
char _bstr[SLEN], a_str[SLEN];
printf("please input string:\'_bstr\'!\n");
s_gets(_bstr, SLEN);
printf("please input a object string:\'a_str\'!\n");
s_gets(a_str, SLEN);
int a_len = strlen(a_str);
unsigned A_ws = _FindChar(_bstr, a_str);
if (A_ws == -1) { printf("Error,No found!"); system("pause"); exit(0); }
else
printf("起始:%u,%c,%c\n", A_ws, _bstr[A_ws], _bstr[A_ws + a_len-1]);
system("pause");
return 0;
}
//假设在任何编译器中字符串都可以用下标法访问
int _FindChar(char *_bstr, char *a_str)
{
int a_len = strlen(a_str), b_len = strlen(_bstr);
int LandLen[32], LL = 0;//LL用于记录首字母与目标字符串相等情况的个数,然后逐个比较以得出准确的位置,LandLen储存可能位置的数组
int _SunMen = 0;//用于记录与字符串相等的格数
int All_Find, Find_s;//具有函数作用域,用于返回值
if ((strstr(_bstr, a_str)) != NULL)//若存在包含字符串,则开始检索得出数组下标
{
for (int i = 0; i<b_len; i++)//for的特点,可以暂时任意改变第二个的值,然后迭代结束后不会改变第二个值
{
if (_bstr[ i ] == a_str[0])
{
LandLen[LL] = i;
LL++;
}
};
for (int wei = 0; wei<LL; wei++)//迭代LL次
{
int Sen_Var = LandLen[wei];
_SunMen = 0;
for (int s = 0; s<a_len; s++)
{
if (_bstr[Sen_Var] == a_str[s])
_SunMen++;
Sen_Var++;//_bstr字符串的可能正确的位置
Find_s = s+1;
}
if (_SunMen == a_len)//表示a_str字符串中的字符与_bstr中某个项开始的连续的字符全部相等
All_Find = Sen_Var-Find_s;
}
return All_Find;
}
else
return -1;
}
/*for(int m=0;m< ; ) LL a_len b_len */
/*先进行筛选首个字母,得出位置,再进行精选,排除*/
char * s_gets(char *st, int n)
//string.h(strcha()) or stdio.h (fgets())
{
char *ret_val;
char *find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
} |
上一篇: c语言可变参数下一篇: c++ primer plus 6 函数指针梳理&笔记
|