#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int findrstr(const char *str, char ch) {
if(NULL == str) return -1
const char *s = str + strlen(str) - 1
int ix = strlen(str) - 1
for(ix >= 0--ix, --s) {
if(*s == ch) return ix
}
return -1
}
int main(int argc, char *argv[])
{
const char *msg = "hello,world!!!"
printf("%c", msg[findrstr(msg, 'w')])
return 0
}
=====================================问题补充:二楼的是死循环运行不了啊
=====================================
实在抱歉,之前疏忽了,现在已经改好了,再试一下吧:)
=====================================
问题补充:二楼的幸苦了,仔细看了一下你的,好像有点出入,不是自己输入文章,是打开已有文章。还得麻烦你稍稍修改下。谢谢哈
=====================================
根据你的要求,又改了一版,现在已经改好了,再试一下吧:)
给:
#include<stdio.h>
#include<string.h>
#define MAX_size 1000
int flag=1,degree=0
void Index(char str[],char word[],int position[])
{
int i,len_str,len_word,pos_str,pos_word,k=0,word_number=0//word_number代表短文中单词的个数
len_word=strlen(word)
len_str=strlen(str)
for(i=0i<len_stri++)
{
while(str[i]==' '||str[i]==','||str[i]=='.')
i++
word_number++//单词个数加一
for(pos_str=i,pos_word=0pos_str<len_str &&pos_word<len_wordpos_str++,pos_word++)
{
if(str[pos_str]!=word[pos_word])
break
}
if(pos_word==len_word &&(str[pos_str]=='\0'|| str[pos_str]==' '||str[pos_str]==','||str[pos_str]=='.')) //表明找到相等的单词
{
position[k++]=word_number
degree++//相等的次数加1
flag=0
}
else
{
while(str[pos_str]!=' '&&str[pos_str]==','&&str[pos_str]=='.'&&pos_str<len_str)
pos_str++
}
i=pos_str
}
}
void main()
{
char str[MAX_size],word[20],ch
int position[100],i
int k=0
FILE *fp
if((fp=fopen("a.txt","r"))!=NULL)
{
while(1)
{
ch=fgetc(fp)
if(ch==EOF) break
str[k]=ch
k++
}
}
printf("请输入要检索的单词: \n")
gets(word)
Index(str,word,position)
if(flag)
printf("您输入的单词不在短文中。\n")
else
{
printf("您输入的单词在短文中,它共出现 %-d 次\n",degree)
printf("出现的位置为: \n")
for(i=0i<degreei++)
printf("第%-2d个单词\n",position[i])
}
fclose(fp)
}