Several ways of defining string in C language

Time:2021-4-16

1. What is a string?

The so-called string is essentially an array of special characters ending in ‘\ 0’;

 

2. What should be paid attention to in the process of defining strings

Since a string is essentially an array of special characters ending in ‘\ 0’, when defining a string, you must ensure that the last element stored in the string is’ \ 0 ‘.

When we don’t give the specific length of a string, we need to define a string in this way: char string name [] = {elements contained in the string}

Add ‘\ 0’ to the end of the string, otherwise, it is just an array of characters, not the string we need. When we give the specific length of a string,

In this way: char string name [string length] = {element contained in string}; to define a string, you need to make the string length equal to the actual string length

Length + 1, otherwise, it’s just a character array, not the string we need. For specific examples, see the specific format of the definition string.

 

3. Define the specific format of the string

3.1, char string name [string length] = {element contained in string};

Note: if we do not add ‘\ 0’ to the elements contained in the string, then the length of the string should be the actual length of the string + 1;

For example: char name [6] = {t ‘,’O’,’m ‘,’h’,’e ‘};

 

3.2, char string name [] = {element contained in string};

    Note: to define a string in this way, you need to write ‘\ 0’ in {};

For example: char name [] = {t ‘,’O’,’m ‘,’h’,’e ‘,’ \ 0 ‘};

 

3.3, char string name

Note: the underlying principle of defining strings in this way is to convert “tomhe” to {t ‘,’O’,’m ‘,’h’,’e ‘,’, ‘\ 0’};

For example: char name [] = = tomhe “; < = = > char name [] = {t ‘,’O’,’m ‘,’h’,’e ‘,’, ‘\ 0’};

   

 

The specific codes are as follows:

  

#include 
int main()
{
    char str1[6] = {'T', 'o', 'm', 'H', 'e'};
    char str2[] = {'7', '8', '8', '
#include 
int main()
{
char str1[6] = {'T', 'o', 'm', 'H', 'e'};
char str2[] = {'7', '8', '8', '\0'};
char str3[] = "Tomhe789";
printf("str1 = %s\n",str1);
printf("str2 = %s\n",str2);
printf("str3 = %s\n",str3);
return 0;
}
'}; char str3[] = "Tomhe789"; printf("str1 = %s\n",str1); printf("str2 = %s\n",str2); printf("str3 = %s\n",str3); return 0; }

 

 

Recommended Today

Envoy announced alpha version of native support for windows

Author: sunjay Bhatia Since 2016, porting envoy to the windows platform has been an important part of the projectOne of the goalsToday, we are excited to announce the alpha version of envoy’s windows native support. The contributor community has been working hard to bring the rich features of envoy to windows, which is another step […]