leetcode The first question of the 184th weekly match (the strings in the array match)

 

 First, the use of functions

1,strstr(a,b);

Determine whether b is a substring of a, if yes, return from the beginning of b to the end of a

Such as "abcdefgh" "de"

Return "defgh";

If it is not a substring, NULL is returned;

2,memcpy(a,b+n,c);

Copy the b string from the c strings after the nth position to a

(Note: you need to add b [c] = '\ 0' after finishing the function)

Return a string;

Second, malloc opens up two-dimensional strings;

First open up a pointer to a string pointer;

char **arr = (char**)malloc(sizeof(char*)*wordsSize);

After determining the substring suitable for the topic

Open up a string pointer

arr[cnt] = (char*)malloc(sizeof(char)*(strlen(words[i])+1));

 

 

The final code is as follows

 1 char ** stringMatching(char ** words, int wordsSize, int* returnSize){
 2     int cnt = 0;
 3     char **arr = (char**)malloc(sizeof(char*)*wordsSize);
 4     for(int i = 0; i < wordsSize; i++)
 5     {
 6         for(int j = 0; j < wordsSize; j++)
 7         {
8              if (i! = J)
 9              {
 10                  if (strstr (words [j], words [i])! = NULL)
 11                  {
 12                      arr [cnt] = ( char *) malloc ( sizeof ( char ) * (strlen (words [i]) + 1 )); 
 13                      memcpy (arr [cnt], words [i], strlen (words [i]) + 1 );
 14                     // The above two lines + 1 are to open up one more space for arr [cnt] stores the '\ 0' at the end of the words [i] string
 15                     // Because the length returned by the strlen function is a length that does not contain '\ 0'
 16                     // and the arr returned by memcpy after the string The last digit is no '\ 0'
 17                    // Be sure to remember to add '\ 0'! ! Otherwise it will cross the border! 
18                      cnt ++ ;
 19                      break ;
 20                  }
 21              }
 22          }
 23      }
 24      * returnSize = cnt;
 25      return arr;
 26  
27  
28 }

 (I hope that the next easy question will not copy homework  ̄ω ̄)

Guess you like

Origin www.cnblogs.com/luoyoucode/p/12688777.html