A string is represented in C language as a null-terminated character array. Strings can be created through literals or using the malloc() function; characters can be accessed through the [] operator, but strings are immutable and need to be modified using functions such as strcpy(); in addition, there are multiple string manipulation functions, such as strchr () and strtok() are used to find characters and decompose strings.
Usage of string in C language
What is string?
string is a data type representing text strings in C language. It is a null character ('\0') terminated character array.
Create string
There are two main ways to create a string:
Literal definition:
<code class="c">char s[] = "Hello World";</code>
Use malloc() function to allocate memory:
<code class="c">char *s = (char *) malloc(length + 1); strcpy(s, "Hello World");</code>
Access characters in string
You can use the character array index operator [] to access a single character in a string:
<code class="c">printf("%c", s[0]); // 输出 'H'</code>
Modify string
string in C language is Immutable. To modify a string, you must use the following function:
String operation functions
There are other string operation functions in the C language, such as:
Example
The following code snippet demonstrates the use of string in C language:
<code class="c">#include <stdio.h> #include <string.h> int main() { // 创建一个 string char s[] = "Hello World"; // 打印 string 的长度 printf("String length: %d\n", strlen(s)); // 修改 string strcpy(s, "Goodbye World"); // 打印修改后的 string printf("Modified string: %s\n", s); return 0; }</code>
The above is the detailed content of How to use string in c language. For more information, please follow other related articles on the PHP Chinese website!