Character functions and string functions

1 Function to find the length of a string

1.1 strlen function

1.1.1 Introduction to strlen function

1. The string has ‘\0’ as the end mark, and the strlen function returns the number of characters that appear before ‘\0’ in the string (excluding ‘\0’).

2. The string pointed to by the parameter must end with ‘\0’.

3. Note that the return value of the function is size_t, which is unsigned (error-prone).

#include <stdio.h>
int main()
{
    const char*str1 = "abcdef";
    const char*str2 = "bbb";
    if(strlen(str2)-strlen(str1)>0)
    {
        printf("str2>str1\\
");
    }
    else
    {
        printf("srt1>str2\\
");
    }
    return 0;
}

//The output result is: str2>str1
//Since the return value of the strlen function is size_t type,
//3-6=-3 is considered an unsigned type, which is a very large number. 
1.1.2 Simulation and implementation of strlen function
//Simulate strlen
//1.Counter
//int my_strlen(char* arr)
//{
// int count = 0;
// while (*arr)
// {
// count + + ;
// arr + + ;
// }
// return count;
//}
//int main()
//{
// char arr[] = "abcdefgh";
// int ret = my_strlen(arr);
// printf("%d\\
", ret);
// return 0;
//}


//2. Do not create temporary variables (function recursion)
//int my_strlen(char* arr)
//{
// if (*arr == '\0')
// return 0;
//else
// return 1 + my_strlen(arr + 1);
//}
//int main()
//{
// char arr[] = "abcdefgh";
// int ret = my_strlen(arr);
// printf("%d\\
", ret);
// return 0;
//}


//pointer-pointer
int my_strlen(char* arr)
{
char* p = arr;
while (*arr != '\0')
arr + + ;
return arr-p;
}
int main()
{
char arr[] = "abcdefgh";
int ret = my_strlen(arr);
printf("%d\\
", ret);
return 0;
}

2 String functions with unlimited length (pay attention to ‘\0’)

2.1 strcpy function

2.1.1 Introduction to strcpy function

1. The source string must end with ‘\0’.

2. ‘\0’ in the source string will be copied to the target space.

3. The target space must be large enough to ensure that the source string can be stored.

4. The target space must be variable.

2.1.2 Simulation and implementation of strcpy function
//Simulate strcpy implementation
#include<assert.h>
char* my_strcpy(char* p1, const char* p2)
{
char* ret = p1;
assert(p1 & amp; & amp; p2);
while(*p1 + + = *p2 + + )
;
return ret;
}
int main()
{
char str1[] = "abcdef";
char str2[] = "qwerty";
//my_strcpy(str1, str2);
printf("%s\\
", my_strcpy(str1, str2));
return 0;
}

2.2 strcct function

2.2.1 Introduction to strcat function

1. The source string must end with ‘\0’.

2. The target space must be large enough to accommodate the content of the source string.

3. The target space must be modifiable.

4. How about appending the string to itself?

Answer: You cannot add it yourself. Your own ‘\0’ mark will be replaced and ‘\0’ will never be found.

2.2.2 Simulate the strcat function
#include<stdio.h>
//Simulate the implementation of strcat


char* my_strcat(char* str1, const char* str2)
{
char* ret = str1;
while (*str1)
str1 + + ;
while (*str1 + + = *str2 + + )
;
return ret;
}


int main()
{
char str1[20] = "abcdef";
char str2[] = "abcdef";
//strcat(str1, str2);
my_strcat(str1, str2);
printf("%s\\
", str1);
printf("%s\\
", str2);
return 0;
}

2.3 strcmp function

2.3.1 Introduction to strcmp function

standard regulation:

If the first string is greater than the second string, a number greater than 0 is returned.

If the first string is equal to the second string, 0 is returned.

If the first string is less than the second string, a number less than 0 is returned.

2.3.2 Simulation and implementation of strcmp function
#include<stdio.h>
//Simulate strcmp
#include<assert.h>
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 & amp; & amp; str2);
while (*str1!='\0' & amp; & amp; *str2!='\0')
{
if (*str1 < *str2)
return -1;
else if (*str1 > *str2)
return 1;
str1 + + ;
str2++;
}
return 0;
}


int main()
{
char str1[] = "abcdefgh";
char str2[] = "abcdffgh";
//int ret = strcmp(str1, str2);
int ret = my_strcmp(str1, str2);
printf("%d\\
", ret);
return 0;
}

3 String function with limited length (regardless of whether there is ‘\0’ or not)

3.1 Introduction to strncpy function

Copy num characters from the source string to the destination space.

If the length of the source string is less than num, after copying the source string, append 0 to the end of the target until num.

3.2 Introduction to strncat function

Append num characters starting from source to destination.

Even if num is longer, only source is appended to destination and then ‘\0’ is added.

No matter how long the source is, it only needs to append num bytes and then add ‘\0’ and it will end.

3.3 Introduction to strncmp function

Compare to Another character is different or a string ends or num characters are all compared.

standard regulation:

When the first num characters of the first string are greater than the first num characters of the second string, a number greater than 0 is returned.

If the first num characters of the first string are equal to the first num characters of the second string, 0 is returned.

If the first num characters of the first string are less than the first num characters of the second string, a number less than 0 is returned.

4 String search

4.1 strstr function

4.1.1 Introduction to strstr function

Find a string within a string.

When found, the address of the first occurrence of str2 in str1 is returned.

If str2 does not exist in str1, NULL is returned.

4.1.2 Simulation and implementation of strstr function
//Simulation implementation strstr
char* my_strstr(const char* str1, const char* str2)
{
char* cp = str1;
char* s1 = cp;
char* s2 = str2;
    //Special processing, when str2 passes a null pointer, str1 is returned directly.
if (*str2 == '\0')
return str1;
while (*cp != '\0')
{
s1 = cp;
s2 = str2;
while (*s1 & amp; & amp; *s2 & amp; & amp; *s1 == *s2)
{
s1 + + ;
s2++;
}
if (*s2 == '\0')
return cp;
cp + + ;
}
return NULL;
}
int main()
{
char str1[] = "abcdef";
char str2[] = "cde";
//char* pch = strstr(str1, str2 + 3);
char* pch = my_strstr(str1, str2);
printf("%s\\
", str2);
printf("%s\\
", str1);
printf("%s\\
", pch);
return 0;
}

4.2 strtok function

4.2.1 Introduction to strtok function

1. The sep parameter is a string that defines the set of characters used as separators.

2. The first parameter specifies a string that contains 0 or more tokens separated by one or more delimiters in the sep string.

3. The strtok function finds the next mark in str, ends it with \0, and returns a pointer to this mark. (Note: The strtok function will change the manipulated string, so the string split using the strtok function is generally a temporary copy and can be modified.)

4. The first parameter of the strtok function is not NULL, the function will find the first mark in str, and the strtok function will save its position in the string.

5. The first parameter of the strtok function is NULL, and the function will search for the next mark starting from the saved position in the same string.

6. If there are no more tokens in the string, a NULL pointer is returned.

4.2.2 Usage of strtok function
int main()
{
char* p = "[email protected]";
const char* sep = ".@";
char arr[30];
char* str = NULL;
strcpy(arr, p);//Copy the data and process the contents of the arr array
for (str = strtok(arr, sep); str != NULL; str = strtok(NULL, sep))
{ /*str = strtok(arr, sep) can be understood as returning the first character address of the first substring*/
printf("%s\\
", str);
}
}

5 Error message reporting function

5.1 strerror function

5.1.1 Introduction to strerror function

Returns the error message corresponding to the error code. Returns the initial address of the error message corresponding to the error.

When an error occurs when the library function is executed, an error code will be stored in the error variable.

Error is a global variable provided by C language. When using it, you need an error.h header file.

5.2.2 Use of strerror function
int main()
{
int i = 0;
for (i = 0; i < 10; i + + )
{
printf("%d: %s\\
", i, strerror(i));//
}
return 0;
}

#include<errno.h>
int main()
{
//Files can be manipulated in C language
//Steps to operate files
//1. Open the file
//2. Read/write
//3. Close the file

FILE* pf = fopen("data.txt", "r");
if (pf == NULL)
{
printf("fopen: %s\\
", strerror(errno));
perror("fopen");
//fopen: xxxxxx
return 1;
}
//read file
//...

//Close file
fclose(pf);

return 0;
}

6 character operations

6.1 Character classification function

6.2 Character conversion function

6.3 Use of character operation functions
#include <ctype.h>

int main()
{
printf("%d\\
", isupper('A'));//Returns 0 for lowercase letters and 1 for uppercase letters
printf("%d\\
", isdigit('2'));//Return 0--9
printf("%c\\
", tolower('A'));//Convert to lowercase
printf("%c\\
", toupper('s'));//Convert to uppercase

char arr[20] = { 0 };
gets(arr);//Continue reading when encountering a space
\t
char* p = arr;
while (*p)
{
//Print the entered letters in lowercase
if (isupper(*p))// *p>='A' & amp; & amp; *p<='Z'
{
*p = tolower(*p);//*p = *p + 32;
}
p + + ;
}
printf("%s\\
", arr);
return 0;
}

7 Memory operation function

7.1 memcpy function

7.1.1 Introduction to memcpy function

1. The function memcpy copies num bytes of data starting from the source location to the destination memory location.

2. This function will not stop when encountering ‘\0’.

3. If there is any overlap between source and destination, the copy results are undefined. It is usually used to handle memory copies without memory overlap.

7.1.2 Simulation and implementation of memcpy function
//Simulating implementation of memcpy
#include<assert.h>
void* my_memcpy(void* str1, const void* str2, size_t count)
{
void* p = str1;
assert(str1 & amp; & amp; str2);
while (count--)
{
*(char*)str1 = *(char*)str2;
str1 = (char*)str1 + 1;
str2 = (char*)str2 + 1;
}
return p;
}


int main()
{
char str1[] = "123456";
char str2[] = "000000";
//memcpy(str1, str2, 6);
my_memcpy(str1, str2, 6);
printf("%s\\
", str1);
return 0;
}

7.2 memmove function

7.2.1 Introduction to memmove function

1. The difference from memcpy is that the source memory block and target memory block processed by the memmove function can overlap.

2. If the source space and target space overlap, you must use the memmove function to handle it.

3. It can handle overlapping memory copies and non-overlapping memory copies.

7.2.2 Simulation and implementation of memmove function
//Simulate implementation of memmove
void* my_memmove(void* dest, const void* src, size_t num)
{
void* ret = dest;
if (dest < src)
{
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
while (num--)
{
*((char*)dest + num ) = *((char*)src + num );
}
}
return ret;
}


int main()
{
char str1[20] = "abcdefghijkl";
//char str2[] = "abcdef";
//memmove(str1 + 2, str1, 3);
my_memmove(str1 + 4, str1 + 2, 3);
printf("%s\\
", str1);
return 0;
}

7.3 memset function

7.3.1 Introduction to memset function

Memory settings, set the first byte of the memory block pointed to by ptr to the specified value value, and set the memory in bytes.

7.3.2 Use of memset function
int main()
{
char arr[] = "hello bit";
memset(arr + 1,'x',4);//Set in bytes
printf("%s\\
", arr);
return 0;
}

7.4 memcmp function

7.4.1 Introduction to memcmp function

Compare num bytes starting from the ptr1 and ptr2 pointers.

The return value is as follows:

standard regulation:

When the first num characters of the string pointed to by ptr1 are greater than the first num characters of the string pointed to by ptr2, a number greater than 0 is returned.

When the first num characters of the string pointed to by ptr1 are equal to the first num characters of the string pointed by ptr2, 0 is returned.

When the first num characters of the string pointed to by ptr1 are less than the first num characters of the string pointed by ptr2, a number less than 0 is returned.

7.4.2 Use of memcmp function
int main()
{
int arr1[] = { 1,2,1,4,5,6 };
int arr2[] = { 1,2,257 };
int ret = memcmp(arr1, arr2, 10);
printf("%d\\
", ret);
return 0;
}

arr1 memory layout arr2 memory layout

The size of the first 9 bytes of arr1 and arr2 is the same, and the return value is 0. The 10th byte arr1 is 0 and arr2 is 1, so the return value is -1.