gpt4 book ai didi

c - 在循环中搜索 C 中的字符序列

转载 作者:太空宇宙 更新时间:2023-11-03 23:44:25 25 4
gpt4 key购买 nike

我正在尝试找到在给定字符数组中查找标签的最有效方法。这些“标签”是随机位于字符数组中的一系列字符。

这是一个例子:给定一个字符数组:{'a','s','s','1','m','s','g','e',' x','x','r','s','1',...}。标记 "ss1" 表示消息的开头,其中包含每个字符,直到找到 "exx" 序列,这是消息结尾的标记,并且它不断在数组中搜索下一个“s1”序列。本例中,这里的消息是“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 数组,并且即使在破译消息后仍然循环,我认为它可能难以实现。

最佳答案

尝试保持一种状态,表示您找到了多少标签的开始和结束。像这样:(即使标签内的消息是任意长度,这段代码也能正常工作)

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++;

关于c - 在循环中搜索 C 中的字符序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37504807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com