大家好,感谢您抽出宝贵时间阅读本文档。
我正在练习,遇到了一种练习。练习说我要手动编写一个函数,该函数可以找到字符串中最后一次出现的索引。现在,我可能已经有人问过这个问题,但是我找不到我的代码有什么问题。它适用于几乎所有实例,但是当单词的最后一次出现在字符串的开头。
时并非如此。我尝试过的:我使用指针来存储我们要查找的句子和单词的ends的地址。然后,我使用了while循环来遍历字符串。如果当前字符与要搜索的单词的last字符匹配,我们将输入另一个while循环来比较这两个字符。如果指向单词开头的指针与我们用来遍历单词的指针相等,则找到单词。
这里是一些代码:
#include <stdio.h>
int find_last( char *str, char *word)
{
char *p, *q;
char *s, *t;
p=str; /* Pointer p now points to the last character of the sentence*/
while(*p!='\0') p++;
p--;
q = word;
while(*q!='\0') q++; /* Pointer q now points to the last character of the word*/
q--;
while(p != str) {
if(*p == *q) {
s=p; /* if a matching character is found, "s" and "t" are used to iterate through */
/* the string and the word, respectively*/
t=q;
while(*s == *t) {
s--;
t--;
}
if(t == word-1) return s-str+1; /* if pointer "t" is equal by address to pointer word-1, we have found our match. return s-str+1. */
}
p--;
}
return -1;
}
int main()
{
char arr[] = "Today is a great day!";
printf("%d", find_last(arr, "Today"));
return 0;
}
因此,此代码应返回0
,但它返回-1
。它可以在我测试过的所有其他实例中使用!
谢谢!
EDIT:在CodeBlocks中运行时,输出符合预期(0
),但是使用任何其他在线IDE,我仍然可以找到输出-1
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
char str[MAX_SIZE];
char word[MAX_SIZE];
int i, j, index, found;
int strLen, wordLen;
printf("Enter any string: ");
gets(str);
printf("Enter any word to search: ");
gets(word);
index = -1;
strLen = strlen(str);
wordLen = strlen(word);
for(i=0; i<=strLen - wordLen; i++)
{
found = 1;
for(j=0; j<wordLen; j++)
{
if(str[i + j] != word[j])
{
found = 0;
break;
}
}
if(found == 1)
{
index = i;
}
}
if(index == -1)
{
printf("\n'%s' not found.", word);
}
else
{
printf("\nLast index of '%s' = %d", word, index);
}
return 0;
}
希望这是您要找的那个。