Differences between char * and string

I want to know the differences between char * and string . for example in this code:

 char *a; string b; 

Can anybody help me?

+6
source share
5 answers

Assuming you reference std::string , string is a standard library class that models a string.

char * is just a pointer to a single char. In C and C ++, there are various functions that will take a pointer to a single char as a parameter and will track from memory until a memory value of 0 (often called a null terminator) is reached. Thus, he models a string of characters; strlen is an example of a function (from the C standard library) that does this.

If you have a choice, use std::string , since you do not need to worry about memory.

+13
source

char* is a pointer to a primitive type: char

string is a first-class object from the standard template library that wraps a lot of functionality (for example, combines two lines) and simplifies working with it.

2 very different objects!

+3
source

Its simple, char *a; declares a pointer to 'a' of type char , it will point to a constant string or character arrays. String b; declares b as an object of type string type.String is a class that contains several string manipulation functions (methods). You can look here for more information: http://www.cplusplus.com/reference/string/string/

The following is one sample program that describes a string object and its member function:

 #include <iostream> #include <string> using namespace std; int main () { string str ("steve jobson"); cout <<"hello the name of steve jobs consists of"<< str.size() << " characters.\n"; return 0; } 

str declared as a string object, and the member function size() is called to get the size of str.

0
source

char* can also be a pointer to the 0 (first) place of the character array. It was often used in C , where using String is not supported.

0
source

If you are worried about functionality, string is a functional char* , then you do not need to worry about space

char *

Declaration / Initialization: char* str = "Use";

appending: XXX

search length: strlen(str); // need to include <string.h> or create your own

line

Declaration / Initialization: string str = "Use";

appending: str += " This!"

search length: str.length() // all in one header file

0
source

Source: https://habr.com/ru/post/947552/


All Articles