1

in c++

when I declare

string string1;

then I'm not able to assign by index as in

string1[0] = 'x';

however if I first put string1 = "somestring"; then I am able to use the assignment through index.

string = ""; 

doesnt work

so I'm wondering why is this. I thought std::string was supposed to have index functionality.

Huangism
  • 16,278
  • 7
  • 48
  • 74

2 Answers2

2

When you default construct a string, it's empty. There are no elements its char array, so [0] doesn't exist. If you construct it by giving it a string, like "somestring", it contains that string and the zeroth index is s.

David
  • 27,652
  • 18
  • 89
  • 138
  • how would one construct a string to be ready to be indexed? string string1[0] ? – user3713215 Jun 07 '14 at 20:31
  • 2
    @user3713215, It sounds like you should get a [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – chris Jun 07 '14 at 20:31
2

When you have string string1; you are declaring an empty string. You have to assign a value to it before you can access a character of the string through an index.

It won't create index 0 of an empty string for you just by string1[0] = 'x'; It will, however allow you to change the value at index 0 if there are characters already there in the string.

You can create a 'preallocated' string of sorts through the constructor: string (size_t n, char c); where n is the number of characters to copy and c is the character to fill the string with. So, for example, you could have std::string string1(5, ' '); which would create a string filled with 5 spaces. You could then use any index from 0-4 in order to put other values in the string (as in your original question - string1[0] = 'x';). http://www.cplusplus.com/reference/string/string/string/

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47