简体   繁体   中英

How to use string and string pointers in C++

I am very confused about when to use string (char) and when to use string pointers (char pointers) in C++. Here are two questions I'm having. which one of the following two is correct?

string subString;
subString = anotherString.sub(9);

string *subString;
subString = &anotherString.sub(9);

which one of the following two is correct?

char doubleQuote = aString[9];
if (doubleQuote == "\"") {...}

char *doubleQuote = &aString[9];
if (doubleQuote == "\"") {...}

None of them are correct.

The member function sub does not exist for string, unless you are using another string class that is not std::string .

The second one of the first question subString = &anotherString.sub(9); is not safe, as you're storing the address of a temporary. It is also wrong as anotherString is a pointer to a string object. To call the sub member function, you need to write anotherString->sub(9) . And again, member function sub does not exist.

The first one of the second question is more correct than the second one; all you need to do is replace "\\"" with '\\"' .

The second one of the second question is wrong, as:

  1. doubleQuote does not refer to the 10th character, but the string from the 10th character onwards
  2. doubleQuote == "\\"" may be type-wise correct, but it doesn't compare equality of the two strings; it checks if they are pointing to the same thing. If you want to check the equality of the two strings, use strcmp .

In C++, you can (and should) always use std::string (while remembering that string literals actually are zero-terminated character arrays). Use char* only when you need to interface with C code.

C-style strings need error-prone manual memory management, need to explicitly copy strings (copying pointers doesn't copy the string), and you need to pay attention to details like allocating enough memory to have the terminating '\\0' fit in, while std::string takes care of all this automagically.

For the first question, the first sample, assuming sub will return a substring of the provided string.

For the second, none:

char doubleQuote = aString[9];
if( doubleQuote == '\"') { ... }

Erm, are you using string from STL?

(ie you have something like

#include <string>
#using namespace std;

in the beginning of your source file ;) )

then it would be like

string mystring("whatever:\"\""");
char anElem = mystring[9];
if (anElem=="\"") { do_something();}

or you can write

mystring.at(9)

instead of square brackets.

May be these examples can help.

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