在循环中搜索C中的char序列

时间:2016-05-28 23:49:52

标签: c arrays loops search

我正在尝试找到在给定char数组中查找标记的最有效方法。这些"标签"是一个在char数组中随机定位的字符序列。

这是一个例子:给定一个char数组:{'a','s','s','1','m','s','g','e','x','x','r','s','1',...}。标记"ss1"表示包含每个字符的消息的开头,直到找到"exx"的序列,该字符串是消息结尾的标记,并且它继续在数组中搜索下一个序列" S1&#34 ;.在此示例中,此处的消息为" msg"。

我的初始设计是(伪代码)

while(array[i] != '\0')
    if(array[i] == 's' && array[i+1] == 's' && array[i+2] == '1'  )
        int j = i+3;
            if(array[j] != '\0' && array[j] == 'e' && array[j+1] == 'x' && array[j+2] == 'x' )
                i += 3;
            else
                print(array[j]);
    else i++; //next char

可能有点瑕疵,但你明白了。有没有更好的办法?我想到了strstr但是因为我在这里处理一个char数组并且在解密消息之后仍然循环,我认为它可能很难实现。

1 个答案:

答案 0 :(得分:1)

尝试维护一个状态,表示您找到了多少标记的开始和结束。这样的事情:(即使标签内的消息具有任意长度,此代码仍然有效)

int state = 0;
int found = 0;
int i = 0,j;
int msgStartIndex;
int msgEndIndex;
while(array[i]){
    if((array[i] == 's' && state == 0) || (array[i] == 's' && state == 1) || (array[i] == '1' && state == 2) ){
        state++;
        if(!found && state == 3){
            msgStartIndex = i+1;
            found = 1;
        }
    }
    else if(!found && (array[i] = 's' && state == 2))
        state = 2;
    else if(!found)
        state = 0;
    if((array[i] == 'e' && state == 3) || (array[i] == 'x' && state == 2) || (array[i] == 'x' && state == 1) ){
        state--;
        if(found && state == 0){
            found = 0;
            msgEndIndex = i-3;
            for(j=msgStartIndex; j < msgEndIndex+1; j++)
                printf("%c",array[j]);
            printf("\n");
        }
    }
    else if(found && (array[i] == 'e') && (state == 2 || state == 1))
        state = 2;
    else if(found)
        state = 3;
    i++;
}

更新了开始代码st1和结束代码ex1

的答案
int state = 0;
int found = 0;
int i=0,j;
int msgStartIndex;
int msgEndIndex;
while(array[i]){
    if((array[i] == 's' && state == 0) || (array[i] == 't' && state == 1) || (array[i] == '1' && state == 2) ){
        state++;
        if(!found && state == 3){
            msgStartIndex = i+1;
            found = 1;
        }
    }
    else if(!found && (array[i] = 's' && (state == 1 || state == 2)))
        state = 1;
    else if(!found)
        state = 0;
    if((array[i] == 'e' && state == 3) || (array[i] == 'x' && state == 2) || (array[i] == '1' && state == 1) ){
        state--;
        if(found && state == 0){
            found = 0;
            msgEndIndex = i-3;
            for(j=msgStartIndex; j < msgEndIndex+1; j++)
                printf("%c",array[j]);
            printf("\n");
        }
    }
    else if(found && (array[i] == 'e') && (state == 2 || state == 1))
        state = 2;
    else if(found)
        state = 3;
    i++;