The road to growth --- C language notes (character array and string functions of constructed types)

Never stop learning by yourself, and never forget that no matter how much you have learned, how much you already know, there is no end to knowledge and learning. Lu Bajin

character array

A character array is an array used to store character data. In the C language, strings are handled as character arrays, and there is no special string variable. Strings are very commonly used, so the C language provides many functions that deal specifically with strings.

Definition of character array

A character array is an array used to store character variables, and each array element stores a character. Character arrays are defined similarly to numeric arrays:

char 数组名[常量表达式];

As with numeric arrays, you need to use subscripts to access character array elements, starting with subscript value 0.

Storage of character arrays in memory

Since character and integer are common, integer arrays can also be used to store character data, but this is a waste of space. It is also possible to define two-dimensional character arrays.

b[0]

b[1]

....

b[5]

.....

b[9]

1

 

 

h

 

y

Initialization of character arrays

1. Assign initial values ​​to array elements one by one, this method is similar to numeric arrays

char c[10]={'c','v','b'};

The last array element is not assigned an initial value, and is automatically assigned a null character (that is, '\0', whose ASCII value is 0, is a non-printing character)

2. Initialize with a string. C language stipulates that a string can be directly assigned to a character array for initialization.

char c[12]={"hello world"};

In fact, the curly braces are often omitted in the actual application process, and even the length of the array is omitted

char c[]={"hello world"};

Note: The storage length is the number of characters in the string + 1, because '\0' as the end character also occupies a length.

The character array can only assign the entire string at one time when it is initialized, and once it is defined, it can only be assigned character by character.

Strings and End-of-String Markers

In the C language, the content enclosed in double quotation marks is a string constant. There is no specific type for storing string variables, strings are stored in arrays of type char terminated by a null character ('\n'). The null character is used to mark the end of the string, so '\ 0' is also called the end of the string or the end of the string. 0' is the 0th character in the ASCII code table, which is called NUL in English and "null character" in Chinese. This character can neither be displayed nor has a control function, and outputting this character will have no effect. With the null character as the terminator of the string, there is no need to judge the length of the string by the length of the character array. It is worth noting that assigning values ​​to the array character by character and initializing will not automatically add '\0', we need to artificially Add to.

References and input and output of character arrays

  1. reference to character array

A reference to a character array is a reference to an element of a character array. Like a character variable, it can be assigned a value, participate in expression operations, or perform input and output. For example:

char c[5];
c[0]='c';
c[4]=c[2]+5;
for(i=0;i<5;i++)
c[i]='a'+i;
for(i=0;i<5;i++)
printf("c[%d]=%c",i,c[i]);

We can use the for statement to output one by one. At the same time, the C standard library also provides us with some functions for our overall input and output, which I will write in the following article.

String input

scanf() function

Use the scanf() function and the conversion character %s to read a string. When reading, the first non-blank character is used as the beginning of the string, and the next blank character is used as the end of the string. Whitespace includes blank lines, spaces, tabs, or newlines.

char a[6];
scanf("%s",a);

Note: The input item a of the scanf() function is a defined character array name, the input string should be shorter than the defined length, the system will automatically add '\0', if the input content is too long, scanf() will also cause Data overflow. At this point we can specify the width to prevent overflow such as: %10s

Special note: In the VS compiler, due to security issues, we need to use scanf_s() instead in actual use. The specific usage method is similar. Similarly, we can also use #define _CRT_SECURE_NO_WARNINGS to ignore this problem.

f58b82737f032ec4cc62fcb8e06c2a52.png

6dbb614cbc788b56c081ee1452299204.png

get() function

When we use the scanf() function for input, we can only enter one character at a time and the input stops when a space is encountered. In order to allow us to input a sentence at a time, the gets() function was born. In fact, the C11 standard committee It has been abolished in VS2022 and we can no longer use it. Here we introduce some of its alternatives.

fgets() function

char *__cdecl fgets(char *_Buffer, int _MaxCount, FILE *_Stream)

It contains three parameters, of which the second parameter indicates the maximum number of characters to be read (specially marked including '\0'), the third parameter indicates the file to be read in, if the data input from the keyboard is read in, Then use stdin 1 (stdin is the standard input stream in C language, generally used to obtain the keyboard input into the buffer) as a parameter, and this identifier is defined in stdio.h. For example:

#include<stdio.h>
int main ()
{
    char a[SIZE];
    fgets(a,10,stdin);
    fputs(a,stdout);
    return 0;
 } 

gets_s() function

char *__cdecl gets_s(char *_Buffer, rsize_t _Size)

It contains two parameters, the second parameter is the maximum number of characters to read.

Note: gets_s() only reads data from standard input, so the third parameter is not needed. If gets_s() reads a newline character, it will be discarded directly instead of stored. If gets_s() reads the maximum number of characters If no newline character is read, the following steps will be performed. First set the first character in the target array to a null character, read and discard subsequent input until a newline character or end-of-file is read, and then return a null pointer. Then, an implementation-dependent "handler function" (or other function of your choice) is called, possibly aborting or exiting the program.

string output

printf() function

The conversion specifier %s can be used to output a string, and the output will stop when the terminator '\0' is encountered during output.

#include<stdio.h>
int main()
{
    char a[] = "China";
    printf("%s", a);
    
    return 0;
}

7cabac96650d9897bcaf1b1b03602ebc.png

puts() function

It is used to output a string or a string stored in a character array (a character sequence ending with '\0') to the terminal, and automatically add a newline at the end. The puts() function is often paired with the gets() function use.

#include<stdio.h>
int main()
{
    char a[20] = "Input a string ";
    puts(a);
    fgets(a, 10, stdin);
    puts("This string is");
    puts(a);
    return 0;
}

Note: The puts() function will stop outputting when it encounters a null character, so make sure to include a null character

char a[]={"a","c"}
//这种情况是不会自动添加'\0'

string processing functions

The C language function library provides multiple functions for processing strings. The most commonly used functions include strlen(), strcpy(), strncpy(), strcat(), strcmp(), strlwr(), and strupr(). Its function prototype is in the header file string.h.

strlen() function

The strlen() function is used to count the length of the string, that is, the number of characters contained in the string, but excluding the string terminator '\0'. String can be a character array or a string constant

unsigned int strlen(char*str);//函数原型

 

#include<stdio.h>
int main()
{
    char str[20];
    fgets(str,20,stdin);
    printf("Length of\"%s\"is%d.\n", str, strlen(str));
    printf("Length of\%s\is%d.","abcdefg",strlen("abcdefg"));
    return 0;
}

fccc9ac9cfa41cdcd1eac56f3613aa80.png

Note: The escape character expression is used when outputting double quotes

strcpy() function and strncpy()

Character arrays are the same as numeric arrays, which cannot be assigned and copied as a whole, but can only be assigned or copied one by one. If you want to copy as a whole, you can use the strcpy() function

strcpy(字符数组1,字符数组2);
char* strcpy (char* szCopyTo, const char* szSource);
//函数原型

Note: The strcpy() function is used to assign a string or character array to character array 1, including the string terminator '\0' after the assignment string.

The strcpy() function does not check whether the destination space is sufficient to accommodate the source string, while strncpy() can specify the maximum number of characters to copy.

stmcpy(字符数组1,字符串2,最大长度)
char* stmepy (char* szCopyTo, const char* szSource, int n);
函数原型

Note: If the number of characters in string 2 is less than n, then copy the entire string (including null characters); the maximum length of the copy cannot exceed n, if the number of characters in string 2 is greater than or equal to n, then only copy the first n characters, Null characters are not copied. Null characters do not have to be copied, you can manually add one when needed.

#define _CRT_SECURE_NO_WARNINGS//添加原因见上方
#include<stdio.h>
#include<string.h>
int main()
{
    char str1[20], str2[20] = "hello world";

    strncpy(str1, str2, 5);

    str1[5] = '\0';

        puts(str1);
    return 0;
}

 

0f71905b107250dc6a5caaf18e5387a5.png

strcat() function

The strcat() function is used to connect string 2 to the back of the string in character array 1, and return the starting address of character array 1, and string 2 remains unchanged. It can be a character array or a string constant.

strcat(字符数组1,字符数组2);
char*strcat (char* szAddTo, const char* szAdd);
//函数原型
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main()
{
    char str1[20], str2[10];

    printf("strl:");

    fgets(str1,20,stdin);
    printf("str2:");
    fgets(str2, 20, stdin);
    strcat(str1, str2);

    printf("str1: %s", str1);

    return 0;
}

6bb8d5d44d032a40051cb2438dfbea8c.png

Note: The strcat() function will not check whether the space of the character array 1 is sufficient, and the programmer should ensure that the length of the character array 1 is sufficient to connect the string 2, otherwise an out-of-bounds error will occur. When connecting, remove the string terminator '0' in character array 1, connect each character of string 2 to the last character of character array 1 in turn, and add a string terminator at the end of the new string '\0'.

strcmp() function

The strcmp() function is used to compare strings. If the two strings are the same, it returns 0; when string 1 is greater than string 2, it returns a positive integer; when string 1 is smaller than string 2, it returns a negative integer. The comparison of character strings starts from the first character of each character, and compares them one by one (according to the size of the ASCII code value of the characters). If the previous corresponding characters are the same, the comparison will continue until the first pair of different characters is encountered, and the size of the pair of characters will be used as the result of string comparison. string1 and string2 can be character arrays or string constants.

 

strcmp(字符串1,字符串2);
int strcmp (const char* sz1, const char* sz2);
//函数原型
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main()
{
    printf("%d ",strcmp("abc", "abd"));
    printf("%d ",strcmp("abcd", "abc"));
    printf("%d ", strcmp("abc", "abc"));
    return 0;
}

c32b22312484546078ca3944d1ac155a.png

Note: If "ab"<"abd", strcmp("abc", "abd") returns a negative integer; if "abed"> "abe", then strcmp("abed", "abe") returns a positive integer; Stremp("abc", "abe") returns 0 if "abe" is equal to itself. Most of the time, the strmp() function is used to compare two strings for equality or to sort them alphabetically, it doesn't matter exactly what value is returned.

strlwr() function and strupr() function

The strlwr() function is used to convert the uppercase letters in the specified string to lowercase letters and return it.

The strupr() function is used to convert the lowercase letters in the specified string to uppercase letters and return it.

strlwr(字符串)
char* strlwr (char* szToConvert);
//函数原型
strupr(字符串)
char* strupr (char* szToConvert);
//函数原型
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main()
{
    char str[20];
    fgets(str,10,stdin);
    printf("%s\n", _strlwr(str));
    fgets(str,20,stdin);
    printf("%s\n", _strupr(str));
    return 0;
}

220728d05971d8e7ea42747378dcba17.png

 

Last words: If you think this article is helpful to you, I hope you can pay attention to it. Your attention is the motivation for me to continue writing, thank you all.

 

 

99cccdf3f0754123bab8b97fb2978871.gif

 

 

Guess you like

Origin blog.csdn.net/weixin_73602725/article/details/130330912