Bele
Bele

Reputation: 25

C++ change char in string

if i want to change a single char in a string i can do:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string mystring = "Hello";
  mystring[0] = 'T';
  cout << mystring;
  return 0;
}

If i want to change i single char in a string using a different function:

#include <iostream>
#include <string>
using namespace std;

void changeStr(string* mystring);

int main() {
  string mystring = "Hello";
    changeStr(&mystring);
  cout << mystring;
  return 0;
}

void changeStr(string* mystring)
{
    mystring[0] = 'T';
}

Why isnt it working? The whole string gets changed to "T". Im new to programming and still got some problems with pointers / address. I know that a array of char (char[]) is a pointer to its first index. Does this apply to a string aswell? How can i fix it?

Upvotes: 1

Views: 229

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

For starters there is no sense to pass an object of the type std::string to the function through a pointer to the object. You could pass it by reference. So the function could look like

void changeStr(string &mystring)
{
    mystring[0] = 'T';
}

Correspondingly the function is called like

changeStr(mystring);

As for your problem then at first you need to dereference the pointer and only after that to apply the subscript operator

void changeStr(string* mystring)
{
    ( *mystring )[0] = 'T';
}

Alternatively you could write

void changeStr(string* mystring)
{
    mystring->operator []( 0 ) = 'T';
}

Pay attention to that the postfix subscript operator has a higher precedence than the dereferencing operator.

As for the statement in your demonstration program within the function

mystring[0] = 'T';

then actually it assigns the character 'T' to the string using the assignment operator

basic_string& operator=(charT c);

instead of assigning only the first character of the string.

That is after this statement the string will be equal to "T".

It is the same if in main to write

mystring = 'T';

The expressions *mystring and mystring[0] where mystring has the pointer type std::string * are equivalent. So within the function you could even write

mystring[0][0] = 'T';

instead of

( *mystring )[0] = 'T';

Though as I pointed to early it is much better to pass the string by reference.

Upvotes: 1

user18476992
user18476992

Reputation: 1

you don't need to pass the pointer. Simply pass it by reference(reference will update the value) if you pass it by pointer then return the string instead of void.. better option .. pass it by reference

 #include <iostream>
 #include<string>
 using namespace std;
 void changeStr(string &mystring);

 int main() {
 string mystring = "Hello";
  changeStr(mystring);
 cout << mystring;
 return 0;
}

void changeStr(string &mystring)
{
  mystring[0] = 'T';
}

Upvotes: 0

Related Questions