简体   繁体   中英

How can I change the character a string pointer points to?

It's simple enough in theory:

If I have a string animal = "Boar" ;

How can I point animal to the 'O' ?

I've tried this:

int main(int argc, char** argv) {

    string *spoint = new string;
    string word = "Hello";
    spoint = &word;
    spoint++;
    cout << (*spoint);

    return 0;
}

And it doesn't work.

I want cout << word; first to print "Word" , if that's the string word points to, then run an operation, so cout << word; will print "ord" .

There must be a simple way?

I think you are missing some basic pointer arithmetic . Lets take the following code snippet:

 int* spoint;
 spoint++;

If spoint points to a int whose address is 1000 ,then after the above operation, spoint will point to the location sizeof(int) bytes next to the current location, because the next int will be available at 1000 + sizeof(int) .This operation will move the pointer to the next memory location 1004 (if size of int is 4 bytes) without impacting the actual value at the memory location.

Same case is with the strings.

string word[] = {"Hello","world"};
string* spoint = word;
spoint++;

After the spoint++ the spoint will point to "world" not to the char e of "Hello" , that is why you didn't the right output.If you want to access the characters in the string you should use a char* as mentioned by others.

First you have to convert word into a C-string (a null-terminated sequence of characters),while assigning it to char* ,then you can increment it to access the characters.

string word = "word";
const char *spoint = word.c_str();
spoint++;
cout <<spoint<<endl;

Now the spoint will point to the 'o' of "word" after incrementing,and if you will print it using cout then output will be "ord" .

I feel like you are confusing char * with C++ string objects.

By using both you can achieve something similar to what you are asking --although I am not sure that this is what you really want

int main(int argc, char** argv) {

    string word = "Hello";
    const char* spoint = word.c_str()
    spoint++;
    cout << (*spoint);

    return 0;
}

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