Positions in a String and string::npos

The characters in a string have numbered positions, starting at 0, just like the values in an array. We can refer to the position (or index) of a character or a group of characters in a string. Remember, we start counting at 0. For example, here is the string "house" together with the position (or index) of each character.

We can use the position to access the value stored at that location.
string str = "house";
string::size_type len = str.length();
str[0] = 'm';                  
for (int i=0; i < len ; i++)          
cout << str[i] << endl;

If a function were to return the position of the letter 'u' in this string, it would return 2; similarly, the string "use" appears starting in position 2 of this string. The letter 'x' is not found. A function that tries to find something which is not present in a string returns string::npos. Can’t use 0 is used to indicate that a value is not found because 0 would mean position 0 of the string. The value npos is the maximum number of characters that a string can hold, which is one greater than the largest possible character position. (Notice that the string above has 5 characters, but the largest position is 4.)  The exact value of npos is machine dependent and irrelevant; what matters is that it represents a value which cannot be an index into the string.

Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: