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:
char s[] = "Hello World";
Use malloc() function to allocate memory:
char *s = (char *) malloc(length + 1); strcpy(s, "Hello World");
Access characters in string
You can use the character array index operator [] to access a single character in a string:
printf("%c", s[0]); // 输出 'H'
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:
#include#include 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; }
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!