int findbyindex(char* s, char* t, int index);
此自定义函数返回字符串t在s字符串中的首个字符的下标位置
C 库函数 size_t strlen(const char *str)
计算字符串 str 的长度,直到空结束字符,但不包括空结束字符
该函数返回字符串的长度。
代码实现
#include<stdio.h>
#include<string.h>
int findbyindex(char* s, char* t, int index)
{
if (index <= 0 || s == NULL || t == NULL)
return -1;//输入出错
int s_index = index;//用于遍历s字符串的下标
int t_index = 0;
int s_len = strlen(s);
int t_len = strlen(t);
while (s_index<=(s_len-1)&&t_index<=(t_len-1))
{
if (s[s_index] == t[t_index])//相等继续遍历
{
s_index++;
t_index++;
}
else//不相等
{
s_index = s_index - t_index + 1;//下标回到开始比对的位置的下一个位置
t_index = 0;
}
}
if (t_index == t_len)
{
//找到了
return s_index - t_len;//返回下标开始比对的位置
}
else
{
return 0;
}
}
int main()
{
char s[15] = "hellanuluoss";
char t[7] = "luo";
int back=findbyindex(s, t,0);
printf("t字符串在s字符串中的下标位置%d", back);
return 0;
}
运行结果
-数据结构练习代码如有错误欢迎指正
-参考书籍《大话数据结构》