我有一个程序,要求用户输入几个字符。我的程序有大量的字母,将搜索,以查看是否可以找到用户的输入。如果找到,则将打印其值的索引。如果在阵列中找到多个输入副本,则将打印所有索引。
如果用户输入*字符,可以将其视为任何字母并将被忽略,例如AB *可能是ABA,ABB,ABC等等。
我的函数searchArray确定了通配符*。
char* searchArray(char *DNA, char *string)
{
if (!*string)
return NULL;
char *p1 = (char*)DNA;
while (*p1)
{
char *p1Begin = p1,
*p2 = (char*)string;
while ((*p1 && *p2 && *p1 == *p2) || *p2 == '*')
{
p1++;
p2++;
}
if (!*p2)
return p1Begin;
p1 = p1Begin + 1;
}
return NULL;
}
我在我的主程序中调用此函数来比较字符串,然后如果字符串匹配,我将打印它的位置索引。但是我似乎无法打印超过1个索引(如果有多个集合,则不会打印)。
char * result = searchArray(DNA, inputstring);
while (result != NULL)
{
int position = result - DNA;
printf("Match found at element %d", position);
result = strstr(++result, inputstring);
}
答案 0 :(得分:0)
以下代码
strstr()
有一些边缘情况会有问题,但是,你可以处理那些
#include <stdio.h>
#include <string.h>
int main( void )
{
// DNA must be an array, not a pointer to an array
char DNA[] = { "zabcdefghijklmnab defghijk ab 123 ab" };
// findString must be an array, not a pointer to an array
char findString[] = {"ab*"};
// always a good idea to initialize variables on the stack
char *wildCard = NULL;
// Note following 'if' will not result in correct action if
// wildcard character not last in findString
if( ( wildCard = strstr( findString, "*") ) )
{ // then a trailing '*', so replace with NUL byte
*wildCard = '\0';
}
// get first possible pointer to where findString is in DNA string
char * result = strstr( result, findString );
while( result )
{ // then an instance of the findString found in DNA string
int position = result - DNA;
printf("Match found at element %d\n", position);
// Note: step over first byte of instance of findString
// may want to change +1 to length of original findString
result = strstr( result+1, findString );
}
return 0;
} // end function: main