一个C问题,求教

CloudStrifers 2011-04-22 10:16:13
编写一个函数strindex(s,t)它返回字符串t在s中最右边出现的位置。如果s中不包含t,则返回-1.例如字符串“ab”在字符串“abcdefabed”中左右边出现的位置应该是7
...全文
183 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
CloudStrifers 2011-04-23
  • 打赏
  • 举报
回复
好的,谢谢了。![Quote=引用 6 楼 svtanto 的回复:]
不好意思,没看清题目,是要封装成函数的。再贴一次。

C/C++ code

#include <stdio.h>
#include <string.h>

// 取得sub在src中从右向左的第一个匹配位置
// 如果sub在src中没有匹配,返回-1
int
strinstr(
const char *src,
const char *sub
……
[/Quote]
某某9 2011-04-23
  • 打赏
  • 举报
回复
strchr
hooha 2011-04-22
  • 打赏
  • 举报
回复
<string.h>中有strchr函数,返回的是找到的第一个符合要求的字符的指针,完了自己可以调整一下就得到了所要求的index。不过这种东西刚开始可以自己当做练习动手实现实现~~~
sunqiyuan1985 2011-04-22
  • 打赏
  • 举报
回复
好像库函数里面没有strrstr 有strrchr
svtanto 2011-04-22
  • 打赏
  • 举报
回复
不好意思,没看清题目,是要封装成函数的。再贴一次。

#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;
}
svtanto 2011-04-22
  • 打赏
  • 举报
回复
我写个简短的例子供楼主参考。

#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;
}
pathuang68 2011-04-22
  • 打赏
  • 举报
回复
string中find_last_of函数,可以轻松搞定。
luciferisnotsatan 2011-04-22
  • 打赏
  • 举报
回复
用c库的strrstr函数就行了
whosyour_dady 2011-04-22
  • 打赏
  • 举报
回复
从后面往前面比较,有就跳出循环
书虫 2011-04-22
  • 打赏
  • 举报
回复

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧