Recently, I encountered the problem of splitting and matching strings (hdu5311), it seems that someone else's code, only know that there are strncpy () and strstr () function, so collect a bit of information, record the basic usage.
First, strncpy ()
char * strncpy (char * destination, const char * source, size_t num);
strncpy () in the <string.h> header file (<cstring> in C + +), copy the part of the original string s in the length of Num to the target string d.
#include <stdio.h> #include <string.h>int main () { char source[] = "Hello World"; Char str1[20]; Char str2[20]; Copy the string from 0 to 5 in source strncpy (str1, source, 6);//0~5:6 puts (str1) length; After running the result is Hello //copy of the string from source 1 to 5 strncpy (str2, source+1, 5);//: 5 puts in length ( str2); After running the result is Ello //original string invariant puts (source); After running the result is Hello World return 0;}
In a split string, the original string is not changed, while the starting point of the split is controlled by the pointer, and the end point is indirectly determined by length, which you need to be aware of when using.
Second, strstr ()
const char * STRSTR (const char * str1, const char * str2); char * STRSTR ( char * str1, const char * str2);
Where str1 is the original string, str2 is a matching string, put back where the first str2 appears (pointer)
#include <stdio.h> #include <string.h>int main () { char source[] = "Hello World Hello World"; Char str1[] = "Hello"; char *str2; Find the position where the first Hello appears printf ("%d\n", strstr (source, str1)-source); After running the result is 0 //Find the location where the first world appears str2 = strstr (source, "World"); printf ("%d\n", Str2-source); After running the result is 6 //Find the second world where the occurrence of printf ("%d\n", strstr (source + (Str2-source) + 1, "world")-source); After running the result is return 0;}
Because the pointer is returned, you can calculate it by subtracting the pointer if you need to calculate the position.
Because the position returned is the first to be found, it is necessary to find the position where nth (n > 1) appears, starting at position +1 where the N-1 occurs.
strncpy () and Strstr () split and match lookup strings