Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of string and memory function in C language

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the sample analysis of strings and memory functions in C language. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Foreword:

String is a very important data type, but there is no explicit string type in C language. Strings in C language appear as string constants or are stored in character arrays. The string constant applies to string functions that do not modify it. At the same time, C language provides a series of library functions to manipulate strings, all of which are contained in the header file string.h.

1. Find the string length strlensize_t strlen (const char * str)

The string has'\ 0' as the closing flag, and the strlen function returns the number of characters that appear before'\ 0' in the string (excluding'\ 0')

The string pointed to by the parameter must end with'\ 0'

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

Learn the simulation implementation of strlen function

The source string must end with'\ 0'. The'\ 0' in the source string is copied to the destination space. The target space must be large enough to ensure that the source string can be stored. The target space must be variable. Learn to simulate and realize.

Example 1:

# include # include int main () {int len1 = strlen ("abcdef"); printf ("% d\ n", len1); / / 6 char arr [] = {'a 'axiomagy', 'strlen' (arr); printf ("% d\ n", len2); / / random value return 0;}

Execution result:

Example 2:

Int main () {if (strlen ("abc")-strlen ("abcdef") > 0) printf ("hehe\ n"); else printf ("\ n"); system ("pause"); return 0;}

Execution result:

Because the strlen is not defined at this time, and its default type is unsigned type, then the number obtained by the addition and subtraction of the two unsigned numbers is a very large number, so the final result must be greater than 0.

Simulation implementation of strlen function

(1) counter

# include # include int my_strlen (const char * str) {int count = 0; assert (str! = NULL); while (* str! ='\ 0') {count++; str++;} return count;} int main () {int len = my_strlen ("abcdef"); printf ("% d\ n", len); return 0;}

(2) pointer-pointer

# include int my_strlen (const char * str) {const char * p = str; while (* p! ='\ 0') {pamphlet;} return pripstre;} int main () {int len = 0; char arr [10] = "abcdef"; len = my_strlen (arr) Printf ("% d\ n", len); return 0;}

(3) recursion

Do not create a temporary variable to find the string length

# includeint my_strlen (const char * str) {if (* str=='\ 0') return 0; else return 1+my_strlen (str+1);} int main () {int len = 0; char arr [10] = "abcdef"; len = my_strlen (arr); printf ("% d\ n", len); return 0 2. String function strcpychar* strcpy (char* destination, const char* source) with unlimited length

Copy the C string pointed by source to the array pointed by destination, including the terminating null character (and stop at that time)

The source string must end with'\ 0'

The'\ 0' in the source string is copied to the destination space

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

The target space must be variable. Learn to simulate and realize

Example:

# include int main () {char arr1 [] = "abcdefghi"; char arr2 [] = "bit"; / / error demonstration / / char * arr1 = "abcdefghi"; / / p points to a constant string, but the constant string cannot be modified / / char arr2 [] = {'baud. / / because'\ 0' is not given at this time, it will cause backward access to strcpy (arr1, arr2); printf ("% s\ n", arr1); return 0;} simulation implementation of strcpy function # include # include char * my_strcpy (char * dest, const char * src) {assert (dest! = NULL); assert (src! = NULL); char * ret = dest / / copy the string pointed to by src to the space pointed to by dest, including'\ 0' while (* dest++ = * src++) {;} / / return the initial address of the destination space return ret;//'\ 0'} int main () {char arr1 [] = "abcdefgh"; char arr2 [] = "bit"; my_strcpy (arr1, arr2); printf ("% s\ n", arr1) Return 0;} strcatchar * strcat (char * destination, const char * source)

Appends a copy of the source string to the destination string. The termination invalid character is overwritten by the first character of the source at the destination and contains a new string of empty characters formed by the concatenation of the destination at the end of the source.

The source string must end with'\ 0'

The destination space must be large enough to accommodate the contents of the source string

The target space must be modifiable

How to append a string to itself

Example:

# include int main () {char arr1 [30] = "hello\ 0xxxxxxx"; char arr2 [] = "wolrd"; strcat (arr1, arr2); printf ("% s\ n", arr1); / / error demonstration char arr3 [] = "hello"; char arr4 [] = "world"; strcat (arr3, arr4); printf ("% s\ n", arr3) / / because the space size of the arr3 array is not defined / / 6 bytes of 'hello\ 0' is opened at this time / / when the arr4 array is appended, an out-of-bounds access is generated, resulting in an error return 0;}

Debugging results:

Execution result:

Summary: at this point, we can see that the string in the arr2 array is appended from the'\ 0' in the arr1 array.

When the string in the arr2 array is appended, the following'\ 0' is also appended.

When the target space is not large enough, the access will be out of bounds.

Simulation implementation of strcat function # include # include char * my_strcat (char * dest, const char * src) {assert (dest! = NULL); assert (src); char * ret = dest; / / 1. Find the'\ 0' while (* dest! ='\ 0') {dest++;} / / 2 of the destination string. Append while (* dest++ = * src++) {;} return ret;} int main () {char arr1 [30] = "hello"; char arr2 [] = "wolrd"; my_strcat (arr1, arr2); printf ("% s\ n", arr1); return 0;} strcmpint strcmp (const char * str1, const char * str2)

This function begins to compare 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 until the terminating null character is reached.

The standard stipulates that:

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.

So how do you judge two strings?

# include # include int main () {char * p1 = "qbc"; char * p2 = "abc"; / / int ret = strcmp (p1, p2); / / printf ("% d\ n", ret); if (strcmp (p1, p2) > 0) {printf ("p1 > p2\ n");} else if (strcmp (p1, p2) = 0) {printf ("p1 = p2\ n") } else if (strcmp (p1, p2)

< 0) { printf("p1 < p2\n"); } return 0;}strcmp函数的模拟实现#include int my_strcmp(const char *str1, const char *str2){ assert (str1 && str2); // 比较 while(*str1++ == *str2++) { if(*str1 == '\0') { return 0;//等于 } } if(*str1 >

* str2) return 1 abcdef / greater than else return-1 abcdef / less / / return (* str1-* str2); / / greater than or less than}} int main () {char * p1 = "abcdef"; char * p2 = "abqwe"; int ret = my_strcmp (p1, p2); printf ("ret =% d\ n", ret); return 0 } 3. String function strncpychar * strncpy (char * destination, const char * source, size_t num) with limited length; / / the unit is bytes.

Copies the first num characters of the source to the destination. If the end of the source C string (represented by an empty character) is found before copying num characters, the destination is populated with zeros until a total of num characters are written.

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 destination until num.

Example 1:

Int main () {char arr1 [10] = "abcdefgh"; char arr2 [] = "bit"; stcncpy (arr1, arr2, 6); return 0;}

Debugging results:

Example 2:

# include # include int main () {char arr1 [10] = "abcdefgh"; char arr2 [] = "bit"; strncpy (arr1, arr2, 6); return 0;}

Debugging results:

Thus it can be seen that the strncpy function can copy characters of any length. When the length of the copied characters is not long enough, it can be supplemented with'\ 0' until the number of copies is equal.

Simulation implementation of the strncpy function # include # include void my_strncpy (char* dest, const char* src, int n) {assert (src); char* p1 = dest; const char* p2 = src; while (NMub -) {* p1cards + = * p2streaming;}} int main () {char arr1 [20] = "hello" char arr2 [] = "world"; my_strncpy (arr1, arr2, 3); return 0 } strncatchar * strncat (char * destination, const char * source, size_t num)

Appends the first num characters of the source to the destination, plus a termination null character

If the length of the C string in source is less than num, only the content before the terminating null character is copied.

Example 1:

# include # include int main () {char arr1 [30] = {"hello\ 0xxxxxx"}; char arr2 [] = "world"; strncat (arr1, arr2, 4); return 0;}

Debugging results:

Example 2:

Int main () {char arr1 [30] = {"hello\ 0xxxxxxxxx"}; char arr2 [] = "world"; strncat (arr1, arr2, 8); return 0;}

Debugging results:

Thus it can be seen that no matter how many numbers are appended, it will add'\ 0' after the appended string, and once the appended number exceeds the length of the appended string, it will end after appending the complete string with'\ 0'.

Simulation implementation of strncat function # include#include#includevoid my_strncat (char* dest, const char* src, int len1, int len2, int n) {char* ret = dest + len1; assert (src); assert (n)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report