[英]Find the rightmost occurrence using strstr() in C
我想在另一個字符串中找到一個字符串的最右邊出現,並返回它的位置。 我看到了三篇類似的文章。 該文章僅使用表格,但我想使用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,但為了保持一致,第一個示例應為索引 10,第二個示例應為位置 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.