[C makes everything] String & memory functions (Part 1)

Welcome to Claffic’s blog Column: “C creates everything | learn C first”

Foreword:

After passing the hurdle of pointers, the next step is the processing of characters in C language. In this issue, we will talk about common character functions and string functions: strlen, strcpy, strcat, memcpy, memmove, memcmp, etc.

Directory

Part1: written in front

Part2: Function Introduction

1.strlen

2. strcpy

3. strcat

4. strcmp

5. strncpy

6.strncat

7. strncmp

8.strstr

9. strtok

10. memcpy

11. memmove

12. memcmp


Part1: Write in front

When it comes to strings, everyone should be familiar with them, but do you know how to deal with strings?

C
The processing of characters and strings is very frequent in languages, but
C
The language itself does not have a string type (this problem was solved in C++ and the string class was introduced), and strings are usually placed in constant strings or
Character array
middle.

string constant
Applies to string functions that do not modify it
.

Part2: Function Introduction

1.strlen

strlen – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strlen/?kw=strlen

size_t strlen ( const char * str );

This function is to get the length of the string, the following are the points to note:

? string has been
‘\0’
As an end sign,
strlen
What the function returns is in the string
‘\0’
The number of preceding occurrences of characters (excluding ‘\0’
);

? The string pointed to by the parameter must end with ‘\0’ ;

? Note that the return value of the function is size_t
, is unsigned.

You can use this function to compare the size of two strings:

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

?operation result:

2.strcpy

strcpy – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strcpy/?kw=strcpy

char* strcpy(char * destination, const char * source );

This function is used to copy the string

Pay attention to parameter passing: Copy the string at the back to the space at the front

? The source string must start with ‘\0’
Finish;

? will replace ‘\0’ in the source string
Copy to target space;

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

? The target space must be mutable.

example:

#include<stdio.h>
#include <string.h>
int main()
{
char str1[40];
const char* str2 = "abc";
char* str = strcpy(str1, str2);
printf("%s\
", str);

return 0;
}

?operation result:

3.strcat

strcat – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strcat/?kw=strcat

char * strcat ( char * destination, const char * source );

This function is to append a string at the end of a string

? The source string must start with ‘\0’
Finish;

? The target space must be large enough to accommodate the content of the source string;

? The target space must be modifiable.

example:

#include<stdio.h>
#include <string.h>
int main()
{
char str[80];
strcpy(str, "these ");
strcat(str, "strings");
strcat(str, "are ");
strcat(str, "concatenated.");
puts(str); // output string, pass char* type, end with \0
return 0;
}

?operation result:

4.strcmp

strcmp – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strcmp/?kw=strcmp

int strcmp ( const char * str1, const char * str2 );

The purpose of this function is to compare two strings

standard regulation:

? The first string is greater than the second string, then return greater than 0
the number of

? If the first string is equal to the second string, return 0;

? The first string is less than the second string, then return less than 0
numbers.

Note Note: Instead of comparing the length of the string, it compares the ASCII code value of the character character by character

example:

#include<stdio.h>
#include <string.h>
int main()
{
char* str1 = "abcdef";
char* str2 = "abcdef";
char* str3 = "abcde";
char* str4 = "cpp";

printf("%d\
", strcmp(str1, str2));
printf("%d\
", strcmp(str1, str3));
printf("%d\
", strcmp(str1, str4)); // the first character is small

return 0;
}

?operation result:

In fact, the biggest function of this function is the case of 0, that is, to judge that two strings are equal.

5.strncpy

strncpy – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strncpy/?kw=strncpy

char * strncpy ( char * destination, const char * source, size_t num );

This function also copies strings, but it has one more parameter num compared to strcpy, indicating that the number of characters of the copied string can be specified.

? copy
num
characters from the source string to the target space;

? If the length of the source string is less than
num
, after copying the source string, append it after the target
0
,until
num
indivual.

example:

#include<stdio.h>
#include <string.h>
int main()
{
char str1[40] = { '0' };
char str2[30] = { '0' };
const char* str3 = "abcdef";

strncpy(str1, str3, 6);
strncpy(str2, str3, 2);

printf("%s\
", str1);
printf("%s\
", str2);

return 0;
}

?Output result:

6.strncat

strncat – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strncat/?kw=strncat

This function also adds n to control the length of characters to be appended

? appends characters,

example:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20];
char str2[20];
strcpy(str1, "To be "); Store To be in str1
strcpy(str2, "or not to be"); store or not to be in str2
strncat(str1, str2, 6); str1 appends 6 characters from str2 or no
puts(str1);
return 0;
}

?Output result:

7.strncmp

strncmp – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strncmp/?kw=strncmp

int strncmp ( const char * str1, const char * str2, size_t num );

Compared with strcmp, it can specify to compare up to num characters

? Compare until another character is different or end of a string or
num
All characters are compared.

example:

#include <stdio.h>
#include <string.h>
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\
", str[n]);
}
return 0;
}

?Output result:

The meaning of this example is to find the string containing R2 in str.

8.strstr

strstr – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strstr/?kw=strstr

char * strstr ( const char *str1, const char * str2);

The function of this function is to find an equal string and return a pointer type

? Look for str2 in str1, if found, return a pointer pointing to the same character in str1 as str2, if not (str2 is not a part of str1), return NULL;

? The matching process does not include empty strings.

example:

#include <stdio.h>
#include <string.h>
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;
}

?Output result:

Simple explanation, look for the string simple in str, save its address in pch, replace simple with sample, and finally output the replaced result.

9.strtok

strtok – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/strtok/?kw=strtok

char * strtok ( char * str, const char * sep );

This function is to do string segmentation

?
sep
The parameter is a string that defines the set of characters used as separators;

? The first parameter specifies a string that contains 0
one or more by
sep

tokens separated by one or more delimiters in the string;

?
strtok
function found
str
and end it with \0, and return a pointer to this tag; (Note: The strtok function will change the string being manipulated, so when using
strtok
The strings split by the function are generally temporary copied content and can be modified. )

?
strtok
the first parameter of the function
No
for

NULL

, the function will find
str
in the first token,
strtok

The function will save its position in the string;

?
strtok
The first parameter of the function is
NULL
, the function will start at the saved position in the same string and look for the next token;

? returns if no more tokens exist in the string
NULL

pointer.

It looks complicated, but in fact…it is complicated.

Let’s look at an example, I believe it will be better:

#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "- This, a sample string.";
char* pch;
printf("Splitting string "%s" into tokens:\
", str);
pch = strtok(str, " ,.-"); // separator can be a set of characters
while (pch != NULL)
{
printf("%s\
", pch);
pch = strtok(NULL, " ,.-");
}
return 0;
}

?Output result:

This example is to cut the string – This, a sample string. according to the three separators, – . Note that when cutting multiple characters, pch = strtok(NULL, ” ,.-“); operation is required, corresponding to The first parameter of the strtok function is NULL, the function will start at the saved position in the same string, and search for the next token

10.memcpy

memcpy – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/memcpy/?kw=memcpy

void * memcpy ( void * destination, const void * source, size_t num );

This void type is not absent, but can accept multiple types

This function is used to copy data

? function
memcpy
from
source
start copying backwards
num
bytes of data to
destination
the memory location of

? This function encounters ‘\0’
when and
Will not
stop;

? if
source

and
destination

With any overlap, the result of the copy is undefined.

example:

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

structure
{
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);// + 1 is to copy '\0'
person. age = 46;

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

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

return 0;
}

?Output result:

Explanation: defines a structure, including name and age, first copy the content in myname to the name member of the structure, and then copy the entire structure to itself (there are many copyable types ).

11.memmove

memmove – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/memmove/?kw=memmove

void * memmove ( void * destination, const void * source, size_t num );

The parameter type is the same as memcpy, what is the difference between the two?

? The difference is that the source memory block and target memory block processed by the memmove function can overlap;

? If the source space and the target space overlap, you have to use the memmove function to deal with it.

That is to say, memmove can ensure that the copied content is correct when it is uncertain whether the source space and the target space overlap, so memmove is safer than memcpy.

example:

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

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

?Output result:

This example can fully demonstrate that the copy can be guaranteed to be successful when the source space and the target space overlap.

12.memcmp

memcmp – C++ Reference (cplusplus.com)https://legacy.cplusplus.com/reference/cstring/memcmp/?kw=memcmp

int memcmp ( const void * ptr1, const void * ptr2, size_t num );

Look at the return type is int type, aha, this function compares two data

? compare from
ptr1

and
ptr2
start of pointer
num
bytes;

example:

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

int main()
{
char buffer1[] = "DWgaOtP12df0";
char buffer2[] = "DWGAOTP12DF0";
int n;
n = memcmp(buffer1, buffer2, sizeof(buffer1));
// Note: the ASCII code value of uppercase characters is smaller than the ASCII code value of lowercase characters
if (n > 0)
printf("'%s' is greater than '%s'.\
", buffer1, buffer2);
else if (n < 0)
printf("'%s' is less than '%s'.\
", buffer1, buffer2);
else
printf("'%s' is the same as '%s'.\
", buffer1, buffer2);

return 0;
}

?Output result:

The ASCII code value of uppercase characters is less than the ASCII code value of lowercase characters

That’s why there is such a result, which is different from what I imagined…

Summary:

This issue is mainly to introduce you to various common string processing functions. You only need to know that there are these useful functions and you can apply them. In the next issue, you will try to implement a few of them.

Code text is not easy

If you think this article is good and helpful to you, please support it