array from string

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;


int main()
{
    string s="Last Assignment/n";
	
	
	    cout<<j[1]<<j[2]<<j[3];


i dont understand how it printing each element of whole string.like L a s.but i did not declared array.how is this possible explain me detialy please .thank you in advance
I don't understand how it is even compiling. Please show your full code.
closed account (j3Rz8vqX)
String is like an array of characters followed by a single character '\0' and possibly even more complex.

String also has many function_methods and several dedicated variables.
http://www.cplusplus.com/reference/string/string/

Hope this helps.

Edit: "How is this possible explain 'in detail' please"
A bit more detail:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   string s="Last Assignment/n";
   //s[0]  =='L';
   //s[1]  =='a';
   //s[2]  =='s';
   //s[3]  =='t';
   //s[4]  ==' ';
   //s[5]  =='A';
   //s[6]  =='s';
   //s[7]  =='s';
   //s[8]  =='i';
   //s[9]  =='g';
   //s[10]=='n';
   //s[11]=='m';
   //s[12]=='e';
   //s[13]=='n';
   //s[14]=='t';
   //s[15]=='/n';
   //s[16]=='/0'; 


The string works similar to a dynamical array.

-What you may not know yet-
It's actually an internal class of the string library and not a primitive.
Last edited on
@Dput

In C++ std::string does not have any termination character! It is only present in a c-type string or a cstring.
By the way, the code for adding a new line in a character is '\n', not '/n'.
closed account (j3Rz8vqX)
@abhishekm71: That's right, c_strings have '\0', thanks.

@Sirolu: I was busy copying and pasting and editing the post to closer explain detail, I accidentally copied his original string.

In this case it wouldn't be the new line character, rather '/' at index 15 and 'n' at index 16.
> dont understand how it printing each element of whole string.like L a s.
> but i did not declared array.

Yes, you did not declare an array; std::string is not an array; it is a user defined type provided by the library.
The type has an overloaded subscript operator, so [] can be be used on objects of type std::string
http://www.cplusplus.com/reference/string/string/operator[]
Topic archived. No new replies allowed.