在 C 語言中,字符串是一系列字符的集合,以空字符(null character,‘\0’)結尾。為了在 C 語言中表示和操作字符串,您需要使用字符數組(char array)或字符指針(char pointer)。
以下是使用字符數組表示字符串的示例:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("The string is: %s\n", str);
printf("The length of the string is: %lu\n", strlen(str));
return 0;
}
在這個例子中,str
是一個字符數組,用于存儲字符串 “Hello, World!”。strlen() 函數計算字符串的長度,不包括空字符。
以下是使用字符指針表示字符串的示例:
#include <stdio.h>
int main() {
const char *str = "Hello, World!";
printf("The string is: %s\n", str);
printf("The length of the string is: %lu\n", strlen(str));
return 0;
}
在這個例子中,str
是一個指向字符常量 “Hello, World!” 的指針。strlen() 函數同樣計算字符串的長度,不包括空字符。注意,我們使用 const char *
而不是 char *
,因為字符串字面值是不可修改的。