13 C language advanced string function memory function

Posted by horsetags on Sun, 16 Jan 2022 20:07:03 +0100

Character function and string function

The analysis of the function part comes from( C + + Resource Network)

  • Find string length
    strlen
  • String function with unlimited length
    strcpy
    strcat
    strcmp
  • Introduction to string functions with limited length
    strncpy
    strncat
    strncmp
  • String lookup
    strstr
    strtok
  • Error message report
    strerror
  • Character operation
  • Memory function operation
    memcpy
    memmove
    memset
    memcmp

String Problems in C language

Characters and strings are frequently processed when writing code, but there is no string type in C language. Strings are usually stored in constant strings or character arrays. A constant string applies to string functions that do not modify it.

Function introduction

1. strlen

1.1 functions:

Get string length gets the string length

Returns the length of a string in C language.

1.2 library function form
size_t strlen ( const char * str );
1.3 precautions:

The length of the string is determined by the terminating character. The length of the string ‎ is as long as the number of characters between the beginning and ending null characters of the string (excluding the ending null character itself).

Note: 1 String ends with '\ 0'. 2. The return value of the function is size_t. Is unsigned.

1.4 examples
int main ()
{
  char szInput[256];
  printf ("Enter a sentence: ");
  gets (szInput);
  printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput));
  return 0;
}

2. strcpy

2.1 functions:

Copy block of memory copy string

Copy the C string pointed by the source to the array pointed by * * target * *, including terminating null characters (and stop at this point).

2.2 library function form
char * strcpy ( char * destination, const char * source );
2.3 precautions:

To avoid overflow, the size of the array pointed to by the target should be long enough to contain the same C string as the source (including terminating null characters), and should not overlap the source in memory.

Note: 1 The source string must end with '\ 0'. 2. The end flag '\ 0' will also be copied. 3. The target space must be large enough. 4. The target space must be variable.

2.4 examples
int main ()
{
  char str1[]="Sample string";
  char str2[40];
  char str3[40];
  strcpy (str2,str1);
  strcpy (str3,"copy successful");
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}

3. strcat

3.1 functions:

Concatenate strings

Append a copy of the ‎ source ‎ string to the ‎ destination ‎ string. The terminating null character in the target is overwritten by the first character of the source and contains a null character at the end of the new string formed by concatenation of the two in the target. ‎

3.2 library function form
char * strcat ( char * destination, const char * source );
3.3 precautions:

There shall be no overlap between destination and source.

Note: 1 Source array must end with '\ 0'. 2. The target space must be large enough to accommodate the contents of the source string. 3. The target space must be modifiable** Important: * * strcat cannot be added by itself.

3.4 examples
int main ()
{
  char str[80];
  strcpy (str,"these ");
  strcat (str,"strings ");
  strcat (str,"are ");
  strcat (str,"concatenated.");
  puts (str);
  return 0;
}

4. strcmp

4.1 functions:

Compare two strings compare two strings

Compare the C string ‎ str1 ‎ with the C string ‎ str2 ‎.

Return valueindicate
<0The value of the first mismatched character in ptr1 is lower than that in ptr2
0The contents of the two characters are equal
>0The value of the first mismatched character in ptr1 is lower than that in ptr2
4.2 library function form
int strcmp ( const char * str1, const char * str2 );
4.3 precautions:

This function starts comparing the first character of each string. If they are equal to each other, continue to use the following pairs until the characters are different or reach the terminating null character.

4.4 examples
int main ()
{
  char key[] = "apple";
  char buffer[80];
  do {
     printf ("Guess my favorite fruit? ");
     fflush (stdout);
     scanf ("%79s",buffer);
  } while (strcmp (key,buffer) != 0);
  puts ("Correct answer!");
  return 0;
}

5. strncpy

5.1 functions:

Copy characters from string copies characters from a string

Copy the first num character of the source to the destination. If the end of the source C string (indicated by a null character) is found before copying num characters, the destination fills with zero until a total of num characters are written to it.

5.2 library function form
char * strncpy ( char * destination, const char * source, size_t num );
5.3 precautions:

If the length of the source exceeds num, the null character will not be implicitly appended to the end of the target.
Therefore, in this case, the target should not be treated as a C string ending in a null value (reading it will overflow).
Destinations and sources must not overlap (when overlapping, see memmove for a safer alternative).

5.4 examples
int main ()
{
  char str1[]= "To be or not to be";
  char str2[40];
  char str3[40];

  /* copy to sized buffer (overflow safe): */
  strncpy ( str2, str1, sizeof(str2) );

  /* partial copy (only 5 chars): */
  strncpy ( str3, str2, 5 );
  str3[5] = '\0';   /* null character manually added */

  puts (str1);
  puts (str2);
  puts (str3);

  return 0;
}

6. strncat

6.1 functions:

Append characters from string

Append the first num characters of the source to the destination, plus a terminating null character.

6.2 library function form
char * strncat ( char * destination, const char * source, size_t num );
6.3 precautions:

If the length of the C string in the source is less than num, only the contents of the null character are copied until termination.

6.4 examples
int main ()
{
  char str1[20];
  char str2[20];
  strcpy (str1,"To be ");
  strcpy (str2,"or not to be");
  strncat (str1, str2, 6);
  puts (str1);
  return 0;
}

7. strncmp

7.1 functions:

Compare characters of two strings

Compare the maximum num characters of C string str1 with the number of characters of C string str2.

7.2 library function form
int strncmp ( const char * str1, const char * str2, size_t num );
7.3 precautions:

This function starts comparing the first character of each string. If they are equal to each other, the comparison continues backward until the characters are different, until the terminating null character is reached, or until the num characters in the two strings match, whichever occurs first.

7.4 examples
int main ()
{
  char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
  int n;
  puts ("Looking for R2 astromech droids...");
  for (n=0 ; n<3 ; n++)
    if (strncmp (str[n],"R2xx",2) == 0)
    {
      printf ("found %s\n",str[n]);
    }
  return 0;
}

8. strstr

8.1 functions:

**Locate substring * * locate substring

Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

8.2 library function form
const char * strstr ( const char * str1, const char * str2 );
      char * strstr (       char * str1, const char * str2 );
8.3 precautions:

The matching process does not include terminating the null character, but it stops when it is encountered.

8.4 examples
int main ()
{
  char str[] ="This is a simple string";
  char * pch;
  pch = strstr (str,"simple");
  if (pch != NULL)
    strncpy (pch,"sample",6);
  puts (str);
  return 0;
}

9. strtok

9.1 functions:

Split string into tokens splits a string into tokens

A series of calls to this function splits str into tags, which are a sequence of consecutive characters separated by any character in the delimiter.

9.1 library function form
char * strtok ( char * str, const char * delimiters );
9.3 precautions:

In the first call, the function requires a C string as an argument to str, and the first character of str is used as the starting position of the scan mark. In subsequent calls, the function needs a null pointer and uses the position after the end of the last tag as the new starting position of the scan.

To determine the beginning and end of a tag, the function first scans the start position for the first character not contained in the separator (that is, the beginning of the tag). The first character contained in the separator is then scanned from the beginning of the tag, which will become the end of the tag. If a terminated null character is found, the scan will also stop.

This end of the token is automatically replaced with a null character, and the function returns the beginning of the token.

After the termination null character of str is found in the call to strtok, all subsequent calls to the function (with null pointer as the first parameter) will return null pointer.

The point at which the last token is found is retained internally by the function for use on the next call (no specific library implementation is required to avoid data contention).

9.4 examples
int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

10. strerror

10.1 functions:

Get pointer to error message string gets a pointer to the error message string

Interpret the value of errnum and generate a string containing a message describing the error condition, as if it were set to errno by the library function.

10.2 library function form
char * strerror ( int errnum );
10.3 precautions:

character string. Further calls to this function may overwrite its contents (no specific library implementation is required to avoid data contention). The error string generated by strerror may be specific to each system and library implementation.

10.4 examples
#include <stdio.h>
#include <string.h>
#include <errno.h>

int main ()
{
  FILE * pFile;
  pFile = fopen ("unexist.ent","r");
  if (pFile == NULL)
    printf ("Error opening file unexist.ent: %s\n",strerror(errno));
  return 0;
}

11. memcpy

10.1 functions:

Copy block of memory

Copy the value of num bytes directly from the location pointed by the source to the memory block pointed by the destination. The underlying type of the object pointed to by the source and destination pointers is independent of this function.

10.2 library function form
void * memcpy ( void * destination, const void * source, size_t num );
10.3 precautions:

The result is a binary copy of the data. This function does not check for any terminating null characters in the source - it always accurately copies numeric bytes.

To avoid overflow, the size of the array pointed to by the target parameter and the source parameter should be at least num bytes and should not overlap (memmove is a safer method for overlapping memory blocks).

11.4 examples
struct {
  char name[40];
  int age;
} person, person_copy;

int main ()
{
  char myname[] = "Pierre de Fermat";

  /* using memcpy to copy string: */
  memcpy ( person.name, myname, strlen(myname)+1 );
  person.age = 46;

  /* using memcpy to copy structure: */
  memcpy ( &person_copy, &person, sizeof(person) );

  printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );

  return 0;
}

12. memmove

10.1 functions:

Move block of memory

Copy the value of num bytes from the location pointed to by the source to the memory block pointed to by the destination.

10.2 library function form
void * memmove ( void * destination, const void * source, size_t num );
10.3 precautions:

Replication works like an intermediate buffer, allowing the target and source to overlap.
The underlying type of the object pointed to by the source pointer and the target pointer is independent of this function; The result is a binary copy of the data. This function does not check for any terminating null characters in the source - it always accurately copies numeric bytes.

To avoid overflow, the size of the array pointed to by the target and source parameters should be at least num bytes.

12.4 examples
int main ()
{
  char str[] = "memmove can be very useful......";
  memmove (str+20,str+15,11);
  puts (str);
  return 0;
}

13. memcmp

13.1 functions:

Compare two strings

Compare the first byte of the memory block pointed to by ptr1 with the first digital byte pointed to by ptr2

Return valueindicate
<0The value of the first byte that does not match in the two memory blocks in ptr1 is lower than the value in ptr2 (if calculated as an unsigned character value)
0The contents of the two memory blocks are equal
>0The value of the mismatched first byte in the two memory blocks in ptr1 is greater than that in ptr2 (if calculated as an unsigned char value)
13.2 library function form
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
13.3 precautions:

Compare the first byte of the memory block pointed to by ptr1 with the first digital byte pointed to by ptr2. If they all match, zero is returned, or a value different from zero indicates which value is greater if they do not match. Note that, unlike strcmp, this function does not stop comparing when it finds a null character.

13.4 examples
int main ()
{
  char buffer1[] = "DWgaOtP12df0";
  char buffer2[] = "DWGAOTP12DF0";

  int n;

  n=memcmp ( buffer1, buffer2, sizeof(buffer1) );

  if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
  else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);

  return 0;
}

Simulation Implementation of function

Simulation Implementation of strlen

//Counter mode
int my_strlen(const char *str) {
    int count = 0;
    while (*str) {
        count++;
        str++;
    }
    return count;
}
//Cannot create temporary variable counter -- implemented recursively
int my_strlen(const char *str) {
    if (*str == '\0')
        return 0;
    else
        return 1 + my_strlen(str + 1);
}
//Pointer implementation
int my_strlen(char *s) {
    char *p = s;
    while (*p != '\0')
        p++;
    return p - s;
}

Simulation Implementation of strcpy

//1. Parameter sequence
//2. Function of function, stop condition
//3.assert
//4.const modifier pointer
//5. Function return value
char *my_strcpy(char *dest, const char *src) {
    char *ret = dest;
    assert(dest != NULL);
    assert(src != NULL);

    while ((*dest++ = *src++)) { ;
    }
    return ret;
}

Simulation Implementation of strcat

char *my_strcat(char *dest, const char *src) {
    char *ret = dest;
    assert(dest != NULL);
    assert(src != NULL);
    while (*dest) {
        dest++;
    }
    while ((*dest++ = *src++)) { ;
    }
    return ret;
}

Simulation Implementation of STR

char *strstr(const char *str1, const char *str2) {
    char *cp = (char *) str1;
    char *s1, *s2;
    if (!*str2)
        return ((char *) str1);
    while (*cp) {
        s1 = cp;
        s2 = (char *) str2;
        while (*s1 && *s2 && !(*s1 - *s2))
            s1++, s2++;
        if (!*s2)
            return (cp);
        cp++;
    }
    return (NULL);
}

Simulation Implementation of strcmp

int my_strcmp(const char *src, const char *dst) {
    int ret = 0;
    assert(src != NULL);
    assert(dest != NULL);
    while (!(ret = *(unsigned char *) src - *(unsigned char *) dst) && *dst)
        ++src, ++dst;
    if (ret < 0)
        ret = -1;
    else if (ret > 0)
        ret = 1;
    return (ret);
}

Simulation Implementation of memcpy

void *memcpy(void *dst, const void *src, size_t count) {
    void *ret = dst;
    assert(dst);
    assert(src);
   /*
   * copy from lower addresses to higher addresses
   */
    while (count--) {
        *(char *) dst = *(char *) src;
        dst = (char *) dst + 1;
        src = (char *) src + 1;
    }
    return (ret);
}

Simulation Implementation of memmove

void *memmove(void *dst, const void *src, size_t count) {
    void *ret = dst;
    if (dst <= src || (char *) dst >= ((char *) src + count)) {
        /*
        * Non-Overlapping Buffers
        * copy from lower addresses to higher addresses
        */
        while (count--) {
            *(char *) dst = *(char *) src;
            dst = (char *) dst + 1;
            src = (char *) src + 1;
        }
    } else {
        /*
        * Overlapping Buffers
        * copy from higher addresses to lower addresses
        */
        dst = (char *) dst + count - 1;
        src = (char *) src + count - 1;
        while (count--) {
            *(char *) dst = *(char *) src;
            dst = (char *) dst - 1;
            src = (char *) src - 1;
        }
    }
    return (ret);
}

Topics: C Back-end