How do you define a string in the C language?

In C language, strings can be defined using character arrays. Strings can be defined in the following ways:

  1. Utilize an array of characters:
char str[6] = "Hello";  // 定义一个长度为6的字符数组来存储字符串"Hello"
  1. Using character pointers:
char *str = "Hello";  // 定义一个指向字符串"Hello"的字符指针

It is important to note that strings defined by character arrays are mutable, while strings defined by character pointers are immutable. If you need to modify a string defined by a character pointer, you can copy it to a character array for modification. For example:

char str[] = "Hello";  // 定义一个字符数组来存储字符串"Hello"
str[0] = 'h';  // 修改第一个字符为小写'h'

In addition, the C language also provides a special string type, which can be manipulated using functions from the string.h header file. For example:

#include <string.h>

char str[6] = "Hello";
int length = strlen(str);  // 获取字符串长度
char copy[6];
strcpy(copy, str);  // 复制字符串

Strings defined in this way are mutable and can be manipulated and handled using string functions.

bannerAds