Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point to a single character within a string

Lets say I have a string named foo with a value of "I dont want to be a c string", and a string pointer named bar.

Is there a way to make bar point to the capital I in the string without converting it to a c string? Pointing to it directly just gives bar a value of "I dont want to be a c string" instead of the value "I", and everything else I have tried just returns errors.

int main() 
{
    string foo = "I dont want to be a c string";
    string *bar = &foo //I want the pointer bar to stay a pointer of type string.
    cout << *bar; //Prints "I dont want to be a c string" when I want it to print "I"
    return 0; //I want bar to point to foo[0].
} 

The goal is not to print out I, but to give the location of I to a pointer of type string without having to convert it to cstring. Im not even sure it is possible.

like image 297
user3331346 Avatar asked Dec 14 '25 12:12

user3331346


1 Answers

To extract a character from the string pointer, you don't have to do additional conversion.

cout << foo[0];
like image 122
user3437460 Avatar answered Dec 16 '25 01:12

user3437460



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!