Common string function implementation! Have your own "library"!

Keywords: C function

  Common string function implementation! Have your own "library"!

Reviewing a few commonly used strings, I think of a more interesting way to review them, which is to write these commonly used string functions by myself. Although it's common for big guys, it's a happy feeling for me to see my.h file included by #include.

Today we'll share a few of the commonly used string functions: strlen, strcat, strcpy, strncpy, strcmp, strlwr, strupr.

First open your editor and create a new file, saving with the suffix.h

 

Write these three lines of code:

 

Then you can write the function in the middle.

 

1. strlen

C library function size_t strlen(const char *str) calculates the length of the string STR until the empty end character is included.

 

As you can see, strlen returns size_t type, size_ What type is t?

You can find such a statement from the official string.h:

 

You can see size_t is actually an unsigned int type

So we can write this line of function declarations:

size_t mylen(const char *a);

Calculates the length of the string until the end of the empty character, but does not include the empty character, so:

size_t mylen(char *a) {
    size_t n;
    for(n=0;a[n];n++);//Don't calculate'\0', so n starts at 0 and ends at'\0'
    return n;
}

 

2. strcat

The C library function char *strcat(char *dest, const char *src) appends the string pointed by SRC to the end of the string pointed by dest.

A pointer is returned, and two pointers need to be passed in, so the following function declaration can be written:

char* mycat(char *a, const char *b);

To append the b string to the end of the a string, the position of the first character in the b string is the position of the last'\0'in the a string. Therefore:

char* mycat(char *a, const char *b); {
    int cnt,i;//Counters for a and b strings
    for(cnt=0;a[cnt];cnt++);//Let cnt point to'\0'of a string first
    for(i=0;b[i];i++) {
        a[cnt++] = b[i];//Append b-string from position'\0'of a-string
    }
    a[cnt] = '\0';//End flag'\0'needs to be added manually
    return a; //Returns the address of a processed string
}

 

3. strcpy

The C library function char *strcpy(char *dest, const char *src) copies the string pointed to by SRC to dest.

It is important to note that if the target array dest is not large enough and the source string is too long, a buffer overflow may occur.

Returns a pointer that requires two pointers to be passed in, so you can write the following function declaration:

char* mycpy(char *a, const char *b);

To copy the b string to the a string, cover the a string with the b string and add a'\0'at the end. Therefore:

char* mycpy(char *a, const char *b) {
    int cnt;//Set a counter control subscript
    for(cnt=0;b[cnt];cnt++)
        a[cnt] = b[cnt];//Overwrite string a with string b
    a[cnt] = '\0';//Manually add a'\0'
    return a;//Returns the address of a processed string
}

 

4. strncpy

The C library function char *strncpy(char *dest, const char *src, size_t n) copies the string pointed to by SRC to dest, up to n characters. When the length of the SRC is less than n, the rest of the dest will be filled with empty bytes.

The declaration in the c library is as follows:

Equivalent to the upgraded version of strcpy above, strncpy can specify how many characters to copy.

Returns a pointer requiring two pointers and a size_t (actually an unsigned integer), so the function declaration comes:

char* myncpy(char *a, const char *b, size_t n);

Copy the first n characters of the b string into a. Just like strcpy, just cover a directly. So:

char* myncpy(char *a, const char *b, size_t n) {
    int cnt;//Counter Control Subscript
    for(cnt=0;cnt<n && b[cnt];cnt++) //When n characters have not been copied and no'\0'points to the b-string
        a[cnt] = b[cnt];//b covers a in the same position
    a[cnt] = '\0';//Add last string end flag
    return a;//Returns the address of a processed string
}

 

5. strcmp

The C library function int strcmp(const char *str1, const char *str2) compares the string that STR1 points to with the string that STR2 points to.

As you can see, the return value is int, which is used to represent the size relationship between str1 and str2. This function is a bit special, usually in the following three cases:

  • When str1 == str2, the return value is 0

  • When STR1 > str2, the return value is 1

  • When STR1 < str2, the return value is -1

However, some compilers return the difference between ASCII codes of the first unequal string when the two strings are not equal, possibly because:

Most cases are 0, 1, -1.

So I started writing function declarations:

int mycmp(const char *a, const char *b);

The comparison rule for strcmp is that characters from left to right are compared by ASCII code values until different characters appear or'\0'is encountered.

Compare not total size!

Comparison by comparison returns 0, 1, -1. Therefore:

int mycmp(const char *a, const char *b) {
    int cnt;//Counter Control Subscript
    int i = 0; //Make a judgement mark
    for(cnt=0;a[cnt] || b[cnt];cnt++) {
        //Execute the following statement when neither a nor b string is empty
        if(a[cnt] > b[cnt]) {
            i = 1;//If you want to return the difference between ASCII codes, change to i=a[cnt]-b[cnt]; that will do
            break;
        }
        else if(a[cnt] < b[cnt]) {
            i = -1;//Ditto
            break;
        }
    }
    return i;
}

 

6. strlwr

The C library function char *strlwr(char *str) is used to convert characters in the string STR to lowercase, converting only uppercase letters that occur in the str without changing other characters.

The incoming pointer returns the pointer, that is, the string to be manipulated and the string to be returned after the operation, so the following function declaration can be written:

char* mylwr(char *a);

The idea of converting uppercase to lowercase is very simple. Scan one by one and convert uppercase letters to lowercase when they appear. It's easy to do with ASCII codes. The difference between uppercase and lowercase ASCII codes is exactly 32, so let's do something interesting:

char* mylwr(char *a) {
    char *b = a;//Since you are going to operate on a, use b to record the address of the string
    for(;*a;a++) {
        //Continue when a does not point to'\0'
        if(*a >='A' && *a <= 'Z') //Determine if a character at position a is an uppercase letter
            *a += 32;//ASCII code with 32 uppercase letters is exactly the lowercase letter
    }
    return b;//Return address of string
}

 

7. strupr

The C library function char *strupr(char *str) is used to convert characters in the string STR to uppercase, converting only lowercase letters that occur in the str without changing other characters.

The incoming pointer returns the pointer, that is, the string to be manipulated and the string to be returned after the operation, so the following function declaration can be written:

char* myupr(char *a);

Just like strlwr's thought, it just changes to lower case to upper case, upper case to lower case plus 32, then lower case to higher case minus 32. Therefore:

char* myupr(char *a) {
    char *b = a;//Record string address
    for(;*a;a++) {
        //When the string has not been traversed, that is, when a does not point to'\0'
        if(*a >='a' && *a <= 'z') 
            *a -= 32;//Using ASCII codes
    }
    return b;//Return address of string
}

 

End

After completing the above steps, the file looks like this:

Now let's write a.c file to test it:

Always remember to put the.h file and the.c file of the test in the same directory and write it on top of the code with #include.

Use:

As with C library functions, use mylen:

#include<stdio.h>
#include"mystr.h"
#define MAX 50
​
int main(int argc, char** argv) {
    char a[MAX], b[MAX];
    gets(a);
    printf("%zd",mylen(a));
​
    return 0;
}

Input:

abcde

Output:

5

Then you can have fun using your own library!

 

Posted by thaven on Fri, 03 Dec 2021 09:35:15 -0800