69,373
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
// 取得sub在src中从右向左的第一个匹配位置
// 如果sub在src中没有匹配,返回-1
int
strinstr(
const char *src,
const char *sub
);
int
main(
const int argc,
const char *argv[]
)
{
char *src = "abcdefabed";
char *sub = "ab";
int pos = strinstr(src, sub);
printf("%s in %s position is %d\n", sub, src, pos);
getchar();
return 0;
}
int
strinstr(
const char *src,
const char *sub
)
/*
说明:取得sub在src中从右向左的第一个匹配位置
如果sub在src中没有匹配,返回-1
*/
{
int result = -1;
int msglen;
int sublen;
int msgidx;
int subidx;
if (src == NULL) {
return result;
}
if (sub == NULL) {
return result;
}
msglen = strlen(src);
sublen = strlen(sub);
msgidx = msglen;
while (msgidx >= sublen) {
subidx = 0;
while (subidx < sublen) {
if (sub[subidx] != src[msgidx - sublen + subidx]) {
break;
}
subidx++;
}
if (subidx == sublen) {
// 因为从0开始计数,所以要加1
result = msgidx - sublen + 1;
return result;
}
msgidx--;
}
// 如果到这里才返回,那么就是-1
return result;
}
#include <stdio.h>
#include <string.h>
int
main(
const int argc,
const char *argv[]
)
{
char *msg = "abcdefabed";
char *sub = "ab";
int msglen = strlen(msg);
int sublen = strlen(sub);
int msgidx = msglen;
int subidx;
while (msgidx >= sublen) {
subidx = 0;
while (subidx < sublen) {
if (sub[subidx] != msg[msgidx - sublen + subidx]) {
break;
}
subidx++;
}
if (subidx == sublen) {
// 因为从0开始计数,所以要加1
printf("%s in %s position is %d\n", sub, msg, msgidx - sublen + 1);
break;
}
msgidx--;
}
getchar();
return 0;
}