简体   繁体   English

C字符串和C ++字符串有什么区别?

[英]What is the difference between the C string and C++ string?

我的意思是C和C ++中字符串的区别是什么?

C does not define string : it only has "perfectly ordinary arrays of characters" and pointers to those arrays; C没有定义string :它只有“完全普通的字符数组”和指向这些数组的指针;

C++ defines it, as a class type, with several properties and methods. C ++将其定义为具有多个属性和方法的类类型。

In C there is no such thing/type as "string". 在C中,没有“字符串”这样的东西/类型。 It is represented as NULL terminated array of characters like char str[256]; 它表示为以NULL结尾的字符数组,例如char str[256]; . C++ has string class in standard library that internally maintains it as array of characters and has many methods and properties to manipulate it. C ++在标准库中具有string类,该string类在内部将其维护为字符数组,并且具有许多操作它的方法和属性。

I fully agree with @pmg answer. 我完全同意@pmg的答案。 But one need to mention some things. 但是需要提及一些事情。 In C programmer must be very careful when he works with C-strings because a) every C-string must be ended with zero code character; 在C语言中,程序员在使用C字符串时必须非常小心,因为a)每个C字符串必须以零代码字符结尾; b) it is very easy to make buffer overrun if buffer size for string is too small. b)如果字符串的缓冲区大小太小,很容易使缓冲区溢出。 Also in C all work with strings goes through functions. 同样在C语言中,所有与字符串一起使用的功能都要经过函数。 It may be programmers nightmare. 这可能是程序员的噩梦。 In C++ things are much simpler. 在C ++中,事情要简单得多。 Firstly, you don't need to care about memory management. 首先,您不需要关心内存管理。 String class allocate additional memory when internal buffer becomes small. 当内部缓冲区变小时,字符串类分配额外的内存。 Secondly, you don't need to care about zero terminating character. 其次,您无需关心零终止字符。 You work with container. 您使用容器。 Thirdly, there are simple methods for working with string class. 第三,有使用字符串类的简单方法。 For example, overloaded operator + for string concatenation. 例如,用于字符串连接的重载运算符+。 No more awful strcat() calls. 不再有可怕的strcat()调用。 Let the work with strings to be simple! 让使用字符串的工作变得简单!

in C++ String objects are a special type of container, specifically designed to operate with sequences of characters.string class defined in string 在C ++中,字符串对象是一种特殊的容器,专门设计用于处理字符序列.string中定义的string类

or in C string is a character sequence terminated with a null character ('\\0'), all functions related to strings defined in string.h 或在C字符串中是一个以空字符('\\ 0')结尾的字符序列,所有与在string.h中定义的字符串有关的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM