[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
String operations are the basic skills of software development. The commonly used functions include String Length solving, string comparison, string copying, string upper, and so on. Another feature that is frequently used but ignored is string search. Word contains string searches, notepad contains string searches, and winxp also has built-in string searches. Therefore, writing your own string searches improves your self-confidence, on the other hand, in some cases, the software operation efficiency can be improved. Next we will discuss the string search methods in three aspects:
1) Search for basic strings
2) KMP search
3) search strings under multi-core cpu
(1) first, we will introduce the common string search methods:
A) whether the pointer is null; otherwise, return
B) judge whether str is '\ 0' and whether the remaining string length is> = the length of the template string. Only one invalid string is displayed, and the function stops running.
C) Compare the content of the string and the template string in sequence. If all the content matches, return. If one does not match, the break jumps out, str is added to 1, and B is converted)
How should we write algorithms? You can write on your own, even on paper.
Char * strstr (const char * str, char * data)
{
Int index;
Int len;
If (NULL = str | NULL = str)
Return NULL;
Len = strlen (data );
While (* str & (int) strlen (str)> = len ){
For (index = 0; index <len; index ++ ){
If (str [index]! = Data [index])
Break;
}
If (index = len)
Return (char *) str;
Str ++;
}
Return NULL;
}
Char * strstr (const char * str, char * data)
{
Int index;
Int len;
If (NULL = str | NULL = str)
Return NULL;
Len = strlen (data );
While (* str & (int) strlen (str)> = len ){
For (index = 0; index <len; index ++ ){
If (str [index]! = Data [index])
Break;
}
If (index = len)
Return (char *) str;
Str ++;
}
Return NULL;
}
To illustrate the correctness of the code, we can write several test cases for testing.
Void test ()
{
Assert (NULL = strstr (NULL, "china "));
Assert (NULL = strstr ("hello, world", "china "));
Assert (NULL! = Strstr ("hello, china", "china "));
}
Void test ()
{
Assert (NULL = strstr (NULL, "china "));
Assert (NULL = strstr ("hello, world", "china "));
Assert (NULL! = Strstr ("hello, china", "china "));
}