简体   繁体   中英

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++ defines it, as a class type, with several properties and methods.

In C there is no such thing/type as "string". It is represented as NULL terminated array of characters like 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.

I fully agree with @pmg answer. 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; b) it is very easy to make buffer overrun if buffer size for string is too small. Also in C all work with strings goes through functions. It may be programmers nightmare. In C++ things are much simpler. 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. 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

or in C string is a character sequence terminated with a null character ('\\0'), all functions related to strings defined in string.h

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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