The C language determines whether a string begins with str2

  • 2020-05-19 05:17:42
  • OfStack

The code is very concise, the function is also very simple, here is no more nonsense, the code is directly dedicated to everyone, there is a need for a small friend can come to reference


#include <stdlib.h>
#include <string.h>
#include <stdio.h>

/** judge str1 Whether or not to str2 At the beginning 
 *  If it's a return 1
 *  Not return 0
 *  Returns the error -1
 * */
int is_begin_with(const char * str1,char *str2)
{
  if(str1 == NULL || str2 == NULL)
    return -1;
  int len1 = strlen(str1);
  int len2 = strlen(str2);
  if((len1 < len2) || (len1 == 0 || len2 == 0))
    return -1;
  char *p = str2;
  int i = 0;
  while(*p != '\0')
  {
    if(*p != str1[i])
      return 0;
    p++;
    i++;
  }
  return 1;
}

/** judge str1 Whether or not to str2 At the end 
 *  If it's a return 1
 *  Not return 0
 *  Returns the error -1
 * */
int is_end_with(const char *str1, char *str2)
{
  if(str1 == NULL || str2 == NULL)
    return -1;
  int len1 = strlen(str1);
  int len2 = strlen(str2);
  if((len1 < len2) || (len1 == 0 || len2 == 0))
    return -1;
  while(len2 >= 1)
  {
    if(str2[len2 - 1] != str1[len1 - 1])
      return 0;
    len2--;
    len1--;
  }
  return 1;
}

You are welcome to play freely and expand


Related articles: