c++ 自带string类 的对象 字符串结尾带不带‘\0’?
黄舟
黄舟 2017-04-17 13:44:57
0
6
778

c++ 自带string类 的对象 字符串结尾带不带‘0’?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(6)
大家讲道理


Picture above

The string type treats '0' as an ordinary character, and the length is increased by one. It can be seen that '0' is not the end character and does not contain special functions. There is no need to add '0' at the end of the string

There is no string type in C language, but a character array is used instead. Generally, character arrays can be of uncertain length.
char * string = "ABCD". How does the compiler know the end of the string? It usually adds '0' at the end. '

小葫芦

std::string and C-style string in C++ are two different strings. The former is a class defined in the standard library, and the latter is an alias for a character array.

  • C-style string: usually ends with

Ty80

0 is the character array in C language used as the end mark. C++ strings do not have this need

巴扎黑

Why not create a string object and print it to see its size?

巴扎黑

When the C language uses a char* pointer as a string, a special character 0 is needed to mark the end position of the pointer when reading the string, which is generally considered the end of the string mark.
The C++ language is object-oriented, and the length information is directly stored in the members of the object. Reading strings can be read directly based on this length, so there is no need for an end tag. Moreover, the end tag is not conducive to reading strings containing 0 characters in the string.

参照std::string的实现 bits/basic_string.h
大家讲道理

String itself is encapsulated and will

#include <iostream>
#include <stdio.h>
#include <string>
using std::string;
using namespace std;


void test1(){
    string s1 = "Hello";
    const char * v1 = s1.data();
    printf("0x%.2x\n", v1[s1.size()]);

    string *s2 = new string("Hello");
    const char * v2 = s2->data();
    printf("0x%.2x\n", v2[s2->size()]);

}

void test2(){
    string s1 = "Hello";
    const char * v1 = s1.c_str();
    printf("0x%.2x\n", v1[s1.size()]);

    string *s2 = new string("Hello");
    const char * v2 = s2->c_str();
    printf("0x%.2x\n", v2[s2->size()]);;
}

int main()
{
    test1();
    test2();
    return 0;
}

The output is all 0x00
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!