嘿所有,我正在尝试找到字符串中字符或字符数的数字位置.我能够弄清楚如何在字符串"abcd"中查看字符"a"的位置,但如果我输入"abcda"它只打印出0,这意味着它只计算第一个实例.我想找到这个字符串的最后或最右边的出现.这是我到目前为止所拥有的:
#include <stdio.h>
main(){
char s[20];
char t[20];
int pp;
printf("Enter a FULL string: \n");
scanf("%s", s);
printf("Enter what you want to find: \n");
scanf("%s", t);
pp = strindex(s, t);
printf("%d", pp);
}
/* string index */
int strindex(char s[], char t[]){
int i, j, k, c;
for (i = 0; s[i] != '\0'; i++){
for (j=i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return i;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
它可能很简单,但我一直在研究它并绞尽脑汁,没有任何东西出来.非常感谢!
您正在寻找strrchr函数.
char *str = strrchr("abcda", 'a');
int index = strlen("abcda")-strlen(str);
Run Code Online (Sandbox Code Playgroud)
您没有在找到事件后立即返回i,而是将i存储在另一个变量中.
即.替换
return i;
为
lastOccurence = i;
lastOccurrence应该在函数开始时初始化为-1,然后在结束时返回.
此外,您的内部循环需要检查s [j]!='\ 0',否则您将在搜索时超过输入字符串的末尾.
归档时间: |
|
查看次数: |
2054 次 |
最近记录: |