我想找到一个字符串在另一个字符串中最右边出现的位置并返回它的位置。我看到了三个这样的帖子This one仅使用表格,但我想使用 strstr()
。 strstr()
的问题是找到字符串最左边的出现位置,但我想要最右边的出现位置,所以我尝试做的是反转 strstr()
并使用这段代码使其从右到左工作。
int StrInd(char *MainStr, char *SecondStr){
int i;
i = strlen(MainStr);
while (i >= 0) {
if ( strstr( (MainStr + i)-1, SecondStr ) != NULL ) { // found it
return i;
}
i--;
}
}
这段代码的问题是,如果字符串只存在一次,它就不会出现。例如,当您给出字符串“halolololele”时,如果您搜索字符串“le”,它将返回 11,但如果您搜索字符串“ha”,它将返回 0。
代码中的缺陷在哪里,为什么它给出不同的值?
这也是完整的代码。
int str_index(char *MainStr, char *SecondStr);
int main(int argc, char *argv[]) {
int Ans, Seclen = 256,Mainlen = 256;
char *SecondStr = malloc(Seclen);
char *MainStr = malloc(Mainlen);
printf("Give the first string: ");
fgets(MainStr,Mainlen,stdin);
printf("Give the second string: ");
fgets(SecondStr,Seclen,stdin);
Ans = StrInd(MainStr,SecondStr);
printf("The position of the string is in: %d", Ans);
free(MainStr);
free(SecondStr);
return 0;
}
int StrInd(char *MainStr, char *SecondStr){
int i;
i = strlen(MainStr);
while (i >= 0) {
if ( strstr( (MainStr + i)-1, SecondStr ) != NULL ) { // found it
return i;
}
i--;
}
}
最佳答案
您的问题表明示例返回位置 11 和 0,但为了保持一致,第一个示例应为 index 10,或者第二个示例应为 position 1.
这显示了一种查找字符串中最右边出现的子字符串的方法(从左侧开始)。只需将每次出现的指针 (+1) 返回到 strstr
中即可,如下所示。
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *ptr = argv[1];
char *found = NULL;
if (argc < 3) {
printf("Syntax: test <string> <substring>\n");
return 1;
}
while ((ptr = strstr(ptr, argv[2])) != NULL) {
found = ptr++;
}
if (found) {
printf("Found '%s' in '%s' at position %u\n", argv[2], argv[1], (unsigned)(found - argv[1] + 1));
} else {
printf("Did not find '%s' in '%s'\n", argv[2], argv[1]);
}
return 0;
}
节目环节:
>test halolololele le
Found 'le' in 'halolololele' at position 11
>test halolololele ha
Found 'ha' in 'halolololele' at position 1
关于c - 在 C 中使用 strstr() 查找最右边的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389725/