- #include <stdio.h>
- int main() {
- char s[] = "I love cat and dog.";
- char c = 'a';
- char *p = s;
- int n = 0;
-
- printf("在"%s"當中搜尋'%c\'。\n", s, c);
- while (*p != '\0') {
- if (*p == c) {
- printf("出現在第%d個字元。\n", p-s+1);
- n++;
- }
- p++;
- }
- if (n == 0)
- printf("無符合字元。\n");
- else
- printf("全部總共搜尋到%d個字元。\n", n);
- return 0;
- }
複製代碼 其中第12行printf("出現在第%d個字元。\n", p-s+1);
我不太明白為何會是p-s+1呢,p-s+1是如何來的? 思考了很久還是弄不懂原理。
請C語言高手指點一二,謝謝! |