文章目录
C语言字符串相关知识
-
C语言没有专门的字符串类型,我们只能使用数组或者指针来间接地存储字符串。
char str1[] = “nihao”;
char *str2 = “hellow wordl”; -
str1 和 str2 是字符串的名字,后边的[]和前边的*是固定的写法。
-
初学者暂时可以认为这两种存储方式是等价的,
-
可通过专用的 puts 函数和通用的 printf 函数输出。
-
这两个函数可以在控制台(显示器)上输出字符串,
puts():输出字符串并自动换行,该函数只能输出字符串。
printf():通过格式控制符%s输出字符串,不能自动换行。除了字符串,printf() 还能输出其他类型的数据。 -
字符串的长度,是字符串包含了多少个字符(不包括最后的结束符’\0’)。例如"abc"的长度是 3,而不是 4。
-
如果只初始化部分数组元素,那么剩余的数组元素也会自动初始化为“零”值,所以只需将第 0 个元素赋值为 0,剩下的元素就都是 0 了。
C语言字符串测试例子
#include <stdio.h>
#include <string.h> // 字符串记得引入该头文件
int test_str()
{
char web_url[] = "www.baidu.com";
char *web_name = "baidu";
puts(web_url);
puts(web_name);
printf("%s\n%s\n", web_url, web_name);
}
//
int test()
{
puts("\x68\164\164\x70://www.nihao.\x6e\145\x74"); // 使用转义字符
return 0;
}
void test_str_len()
{
//char str[] = "http://www.nihao.net/c/";
char str[] = "http";
long len = strlen(str);
printf("The lenth of the string is %ld.\n", len);
}
void test_arr_str()
{
//char str[30]; // 里面是随机值
char str[30] = {0}; // 将所有元素都初始化为 0,或者说 '\0'
char c;
int i;
for(c=65,i=0; c<=90; c++,i++)
{
str[i] = c;
}
//
//str[i] = 0; //此处为添加的代码,也可以写作 str[i] = '\0';
// 它让字符串能够正常结束。根据 ASCII 码表,字符'\0'的编码值就是 0。
printf("%s\n", str);
// ABCDEFGHIJKLMNOPQRSTUVWXYZ口口口口i口口0 ?
}
int main()
{
//test();
//test_str_len();
test_arr_str();
return 0;
}
4万+

被折叠的 条评论
为什么被折叠?



