C 中的字符串是使用字符数组来操作的。数组中的每个字符对应字符串的一个元素,字符串的结尾由空字符('\0')标记。这个空字符至关重要,因为它表示字符串的结尾,并允许函数确定字符串在内存中的结尾位置。
例如,字符串“hello”表示为:
char str[] = {'h', 'e', 'l', 'l', 'o', '\0'};
该数组 str 保存字符串“hello”的字符,并以空字符“\0”结尾,指示字符串的终止。
另一种常见的表示形式是使用字符串文字:
char str[] = "hello";
在这种情况下,编译器会自动在字符串末尾附加空字符“\0”。
字符数组:
您可以通过定义数组的大小并初始化各个字符来创建它们。
例如:
char name[5] = {'J', 'o', 'h', 'n', '\0'};
这将创建一个名为 的字符数组name
,最多可容纳 6 个字符(包括空终止符“\0”)并显式分配每个字符。
字符串文字:
通过将字符括在双引号内来表示:这是一种更短且更方便的表示字符串的方式。
编译器自动附加空字符('\0'):例如:
char greeting[] = "Hello";
在这里,编译器根据字符串文字“Hello”的长度确定数组的大小,并自动添加 null 终止符'\0'
。
空字符('\0')是 C 中的特殊字符,用于标记字符串的结尾。它的 ASCII 值为 0。
在 C 中,字符串以此空字符终止,以指示字符串内容的结尾。对于处理字符串的函数来说,了解字符串的结束位置至关重要。例如,当您使用诸如strlen()
确定字符串长度之类的函数时,它会通过计算字符数直到遇到空字符来计算长度。
例如:
char message[] = "Hello";
该字符串“Hello”存储为'H', 'e', 'l', 'l', 'o', '\0'
.
如果没有空字符,对字符串进行操作的 C 函数将不知道字符串在哪里结束,从而导致未定义的行为或意外结果。
使用 printf() 进行输出:
printf() 函数用于将字符串打印到标准输出(通常是控制台)。
例子:
#include
int main() {
char str[] = "Hello";
printf("The string is: %s\n", str);
return 0;
}
输出:
The string is: Hello
使用 scanf() 作为输入:
scanf() 函数用于从标准输入(键盘)读取字符串。
例子:
#include
int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
return 0;
}
输入:
Enter your name: Kareem
输出:
Hello, Kareem!
注意:scanf("%s", name)
从用户输入中读取字符串,但会在第一个空白字符(空格、制表符、换行符)处停止。
使用 fgets() 作为输入:
该fgets()
函数从标准输入读取一行文本,并在输入中允许空格。
例子:
#include
int main() {
char sentence[50];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
printf("You entered: %s", sentence);
return 0;
}
输入:
Enter a sentence: This is a sentence with spaces.
输出:
You entered: This is a sentence with spaces.
这些示例演示了如何在 C 语言中使用printf()
、scanf()
和fgets()
函数进行字符串输入和输出,从而允许在程序执行期间与字符串进行交互。
在 C 中,标头提供了一组允许操作字符串的函数。一些常用的函数包括:
strcpy()
:该函数将源字符串中的字符复制到目标字符串,直到遇到源字符串中的空字符('\0')。例子:#include
#include
int main() {
char source[] = "Hello";
char destination[20];
strcpy(destination, source);
printf("Destination string after copying: %s\n", destination);
return 0;
}
输出:
Destination string after copying: Hello
strcat()
:此函数将源字符串的内容连接(附加)到目标字符串的末尾。它从目标字符串的空字符 ('\0') 开始,并从源字符串复制字符,直到遇到其空字符。例子:
#include
#include
int main() {
char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
输出:
Concatenated string: Hello World
strlen()
:该函数返回字符串str中的字符数,不包括空字符('\0')。例子:#include
#include
int main() {
char str[] = "Hello";
int length = strlen(str);
printf("Length of the string: %d\n", length);
return 0;
}
输出:
Length of the string: 5
以下是 C 语言中一些额外的常见字符串操作:
strcmp()
:该函数比较str1和str2的内容并返回:
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
strncpy()
:此函数将特定数量的字符从一个字符串复制到另一个字符串。下面的示例将最多 num 个字符从源复制到目标:
char source[] = "Hello";
char destination[10];
strncpy(destination, source, 3); // Copies only 3 characters