c++ string and operator[]

The difference between operations:

  1. string s; s[0]= ‘a’; cout<<s; gives nothing as output.
  2. string s; s+= ‘a’; cout<<s; output: ‘a’.
  3. string s= " "; s[0]= ‘a’; will also print ‘a’

Can anyone please explain this behaviour ?

You are declaring s as a string and not a character array. So you cannot append elements the way you are doing.

1 Like

thanks for your answer
but if I declare string s= " "; s[0]= ‘a’; will print a !

you can replace the characters in string that way but cannot append them at the end of the string

I tried string s=""; s[0]=‘a’; in Dev c++ and it prints nothing.

cout<< s.size(); for above statement is 0.

cout<< s; won’t print anything until there is valid string assignment to s, that causes the size of s to increase from 0.

The only statement that is causing this, i.e., to increase the size of string is the second statement in your question.

Here string s=""; assigns the string with an empty string with 0 length, i.e.,cout<<s.size() is 0.

I think that your statement is string s=" "; //containing a space.

This statement assigns the string s with a valid string of length 1 having first and the only character, a space.

now in the statement you are just replacing the s[0], which is a space by ‘a’.

Here s[0] exists in the string, and there is just a re assignment of the character s[0] of the string.

1 Like

I’m agree with you.
thank you!

@pratku123: yes there is a space in s= " ";
thank you!