c语言字符串与c++字符串
In C, strings are one special kind of array: a string is an array of char
values:
在C语言中,字符串是一种特殊的数组:字符串是char
值的数组:
char name[7];
I introduced the char
type when I introduced types, but in short it is commonly used to store letters of the ASCII chart.
当我介绍类型时,我介绍了char
类型,但简而言之,它通常用于存储ASCII图表的字母。
A string can be initialized like you initialize a normal array:
可以像初始化普通数组一样初始化字符串:
char name[7] = { "F", "l", "a", "v", "i", "o" };
Or more conveniently with a string literal (also called string constant), a sequence of characters enclosed in double quotes:
或者更方便地使用字符串文字(也称为字符串常量),即用双引号引起来的一系列字符:
char name[7] = "Flavio";
You can print a string via printf()
using %s
:
您可以使用%s
通过printf()
打印字符串:
printf("%s", name);
Do you notice how “Flavio” is 6 chars long, but I defined an array of length 7? Why? This is because the last character in a string must be a 0
value, the string terminator, and we must make space for it.
您是否注意到“ Flavio”的长度为6个字符,但是我定义了一个长度为7的数组? 为什么? 这是因为字符串中的最后一个字符必须为0
值,即字符串终止符,并且我们必须为其留出空间。
This is important to keep in mind especially when manipulating strings.
记住这一点很重要,尤其是在处理字符串时。
Speaking of manipulating strings, there’s one important standard library that is provided by C: string.h
.
说到操纵字符串,C: string.h
提供了一个重要的标准库。
This library is essential because it abstracts many of the low level details of working with strings, and provides us a set of useful functions.
这个库是必不可少的,因为它抽象了许多使用字符串的底层细节,并为我们提供了一组有用的功能。
You can load the library in your program by adding on top:
您可以通过在顶部添加来将库加载到程序中:
#include <string.h>
And once you do that, you have access to:
完成此操作后,您可以访问:
strcpy()
to copy a string over another stringstrcpy()
将一个字符串复制到另一个字符串上strcat()
to append a string to another stringstrcat()
将一个字符串附加到另一个字符串strcmp()
to compare two strings for equalitystrcmp()
比较两个字符串是否相等strncmp()
to compare the firstn
characters of two stringsstrncmp()
比较两个字符串的前n
字符strlen()
to calculate the length of a stringstrlen()
计算字符串的长度
and many, many more.
还有很多很多
I will introduce all those string functions in separate blog posts, but just know that they exist.
我将在单独的博客文章中介绍所有这些字符串函数,但只知道它们存在。
c语言字符串与c++字符串