我为什么要过度积累?

时间:2015-02-06 19:55:17

标签: c string for-loop compare accumulator

非常困惑的菜鸟在这里。谁能解释为什么我@ 12和i @ 13正在积累? 我的函数应该查看两个字符串,以查看第二个字符串是否包含在第一个字符串中。我这样做是通过循环遍历两个字符串并比较String1和String2中该索引处的字符。如果累加器的计算结果为较短字符串的长度,则函数将返回1并打印:“它有效”。否则它将返回0.

代码:

#include <stdio.h>
#include <string.h>
int main()
{
    int accum = 0;
    char string1[21];
    char string2[9];
    strcpy(string1, "The test for the lab");
    strcpy(string2, "The test");
    int j = (strlen(string1)-1);
    for(int i = 0; i<=j; i++){
        if(string1[i] == string2[i]){
            accum += 1;
            printf("accum is %d \n",accum);         
            printf("i is %d \n",i);
            printf("string1[i] is %c \n",string1[i]);
            printf("string2[i] is %c \n",string2[i]);           
        }
    }
if (accum == strlen(string2)){
    printf("it works!");
    return 1;
}
else
    return 0;
}

终端输出:

accum is 1 
i is 0 
string1[i] is T 
string2[i] is T 
accum is 2 
i is 1 
string1[i] is h 
string2[i] is h 
accum is 3 
i is 2 
string1[i] is e 
string2[i] is e 
accum is 4 
i is 3 
string1[i] is   
string2[i] is   
accum is 5 
i is 4 
string1[i] is t 
string2[i] is t 
accum is 6 
i is 5 
string1[i] is e 
string2[i] is e 
accum is 7 
i is 6 
string1[i] is s 
string2[i] is s 
accum is 8 
i is 7 
string1[i] is t 
string2[i] is t 
accum is 9 
i is 12 
string1[i] is   
string2[i] is   
accum is 10 
i is 13 
string1[i] is t 
string2[i] is t 
请帮忙!

0 个答案:

没有答案