文章时效性提示
本文发布于 467 天前,部分信息可能已经改变,请注意甄别。
《C程序设计语言》练习4-1
编写函数strrindex(s,t),它返回字符串t在s中最右边出现的位置。如果s中不包含t,则返回-1。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <stdio.h> #include <string.h> int strrindex(char s[],char t[]); int main() { char s[] = "abqqqcdqqefqgqhijkqqqqlmnopqqqqrsqqqqtqrqrqrscsdaadzcqraaaaqqqqqr"; char t[] = "qr"; int Locate = strrindex(s,t); return 0; } int strrindex(char s[],char t[]) { int i = 0; int ret = -1; int tLenth = strlen(t); for (i = 0; s[i] != '\0'; i++) { if (s[i] == t[0]) { int j = 0; for (j = 0; j < tLenth; j++) { static int Count = 0; if (s[i+j] == t[j]) { Count++; if (Count == tLenth) { ret = i; Count = 0; } } else { Count = 0; break; } } } } return ret; }
|
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include <stdio.h> #include <string.h> int strrindex(char s[], char t[]); int main() { char s[] = "abqqqcdqqefqgqhijkqqqqlmnopqqqqrsqqqqtqrqrqrscsdaadzcqraaaaqqqqqr"; char t[] = "qraaa"; int Locate = strrindex(s, t); return 0; } int strrindex(char s[], char t[]) { int sLength = strlen(s); int tLength = strlen(t); int i, j for (i = sLength - tLength; i >= 0; i--) { for (j = 0; j < tLength; j++) { if (s[i + j] != t[j]) { break; } } if (j == tLength) { return i; } } return -1; }
|