c语言字符串与c++字符串_C字符串简介

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 string

    strcpy()将一个字符串复制到另一个字符串上

  • strcat() to append a string to another string

    strcat()将一个字符串附加到另一个字符串

  • strcmp() to compare two strings for equality

    strcmp()比较两个字符串是否相等

  • strncmp() to compare the first n characters of two strings

    strncmp()比较两个字符串的前n字符

  • strlen() to calculate the length of a string

    strlen()计算字符串的长度

and many, many more.

还有很多很多

I will introduce all those string functions in separate blog posts, but just know that they exist.

我将在单独的博客文章中介绍所有这些字符串函数,但只知道它们存在。

翻译自: https://flaviocopes.com/c-strings/

c语言字符串与c++字符串

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值