C语言-字符串

《C语言入门经典》第5版 Ivor Horton 第6章 字符串和文本的应用 读书笔记

6.2 存储字符串的变量

 1.  char 类型数组:

         char saying[20];    存储一个至多包含 19 个字符的字符串

         char saying[ ] = "This is a string."; 没有明确定义这数组的大小,编译器会指定一个足以容纳这个初始化字符串常量的数值

         char str[40] = "To be";     用一个字符串初始 char 类型数组的部分元素

引用:

要引用存储在数组中的字符串时,只需使用 数组名 即可。

       printf("\nThe message is: %s", message);

       %s 说明符用于输出一个用空字符终止的字符串。

确定字符串的长度

#include <stdio.h>
int main(){
	char str1[] = "To be or not to be";
	char str2[] = ", that is the question";
	int count = 0;
	while(str1[count]) // 和下面写法相同,因为 '\0' 字符的ASCII码是 0,对应于布尔值 false
		++count;
	printf("str1.length = %d", count);
	count = 0;
	while(str2[count] != '\0')
		++count;
	printf("str1.length = %d", count);
	return 0;
} 

 2. 字符串数组

        char 类型的 二维数组 ,数组的 每一行 都用来 存储一个字符串。

char sayings[3][32] = {
	"Manners maketh man.",
	"Many hands make light work.",
	"Too many cooks spoil the broth"
}

第一维 指定 数组可以包含的 字符串个数,第二维指定为 32,刚好能容纳最长的字符串(包含 \0 终止字符)

必须指定第二维的大小,可以让编译器计算数组有多少个字符串。上述可以写为:char sayings[ ] [32]

使用 sizeof 运算符 可以确定数组中的字符串个数:

#include <stdio.h>
int main(){
	char str[][70]{
		"He was my North, my South, my East and West,",
		"My working week and my Sunday rest,",
		"My noon, my midnight, my talk, my song;",
		"I thought that love would last forever: I was wrong."
	};
	int count = 0;
	int strCount = sizeof(str)/sizeof(str[0]);
	printf("There are %d strings.\n", strCount);
	// find the lengths of the strings
	for(int i = 0; i < strCount; i++){
		count = 0;
		while(str[i][count])
			count++;
		printf("The String:\n   \"%s\"\n contains %d characters.\n", str[i], count);
	}
	return 0;
}

6.3 字符串操作

1.确定字符串的长度

猜你喜欢

转载自blog.csdn.net/gsj9086/article/details/85537102