Search

17.4 — std::string character access and conversion to C-style arrays

Character access

There are two almost identical ways to access characters in a string. The easier to use and faster version is the overloaded operator[]:

char& string::operator[] (size_type nIndex)
const char& string::operator[] (size_type nIndex) const

  • Both of these functions return the character with index nIndex
  • Passing an invalid index results in undefined behavior
  • Using length() as the index is valid for const strings only, and returns the value generated by the string’s default constructor. It is not recommended that you do this.
  • Because char& is the return type, you can use this to edit characters in the array

Sample code:

Output:

f
abcdeXg

There is also a non-operator version. This version is slower since it uses exceptions to check if the nIndex is valid. If you are not sure whether nIndex is valid, you should use this version to access the array:

char& string::at (size_type nIndex)
const char& string::at (size_type nIndex) const

  • Both of these functions return the character with index nIndex
  • Passing an invalid index results in an out_of_range exception
  • Because char& is the return type, you can use this to edit characters in the array

Sample code:

Output:

f
abcdeXg

Conversion to C-style arrays

Many functions (including all C functions) expect strings to be formatted as C-style strings rather than std::string. For this reason, std::string provides 3 different ways to convert std::string to C-style strings.

const char* string::c_str () const

  • Returns the contents of the string as a const C-style string
  • A null terminator is appended
  • The C-style string is owned by the std::string and should not be deleted

Sample code:

Output:

7

const char* string::data () const

  • Returns the contents of the string as a const C-style string
  • A null terminator is not appended
  • The C-style string is owned by the std::string and should not be deleted

Sample code:

Output:

The strings are equal

size_type string::copy(char *szBuf, size_type nLength) const
size_type string::copy(char *szBuf, size_type nLength, size_type nIndex) const

  • Both flavors copy at most nLength characters of the string to szBuf, beginning with character nIndex
  • The number of characters copied is returned
  • No null is appended. It is up to the caller to ensure szBuf is initialized to NULL or terminate the string using the returned length
  • The caller is responsible for not overflowing szBuf

Sample code:

Output:

black

Unless you need every bit of efficiency, c_str() is the easiest and safest of the three functions to use.

17.5 -- std:string assignment and swapping
Index
17.3 -- std::string length and capacity

10 comments to 17.4 — std::string character access and conversion to C-style arrays

  • Tobi

    Amazing tutorial, thank you! When studying a C++ course at university where pedagogy is not prioritized it’s a bless to have a tutorial like this to learn the basics.

    Even though I know it is not your intent to cover the standard library some examples covering things like iterators, vectors and such would be much appreciated in the future.

  • dragonfi

    Thank you for the great tutorial,

    It really helped me learn to program in c++, and I believe it helped me to write better programs in general.

    The tutorial was really clear and easy to understand, and I found it quite complete already.

    I’m sure I will check back to skim-read one of the harder topics or see if you put up a new chapter for this awesome tutorial.

  • Sanjiin

    Awesome tutorial. I was looking to learn C++ for some game programing. I’m pretty bad at math, but it seems pretty managable the way you present it. Thanks so much.

  • Bishal Thapa

    can anybody write me a programme to open the url using C++ please give the complete programme

  • Slice

    Well, what a journey! Simply amazing tutorial. The best, by far. Clear and concise, exposing exactly what we want to know and mentioning the more advanced or lesser known/used stuff (instead of just not bringing them up at all). You should write a book! I would like to see more chapters added that explore some of the classes that others have suggested throughout the tutorials. I’m sure the information exists somwhere already is merely a Google away, but the way you present information is the best I’ve seen.

    Oh, is there a way to get all of this tutorial in a pre-archived format so that I can download it all as a whole package? Would save me heading online all the time.

    Anyway, thanks and bye.

  • I LOVED YOUR TUTORIAL. Thank you so much.

    I’ve been trying to learn C++ for years, but I always got stucked in the pointers. Finally I understood them.
    I wanted to make games, so I started with BASIC (like 13 years ago), then I learned Visual Basic 6 (bad idea), so when I tried to learn C++ I just cried xD.

    Thanks again!!!!

  • yondchang

    Hi there,

    I do not understand this
    “Using length() as the index is valid for const strings only, and returns the value generated by the string’s default constructor. It is not recommended that you do this.”
    Could anyone help?
    thanks,

    Yang

    • DOBRESCU Mihai

      Hi, Yang.

      Let us see whether the aforementioned paragraph is correct or not:

      ““Using length() as the index is valid for const strings only, and returns the value generated by the string’s default constructor. It is not recommended that you do this.””

      Let us write the following sample program:


      #include <iostream>
      #include <string>

      using namespace std;

      int main()
      {
      const string scSource("abcdefg");
      string::size_type nLength = scSource.length();
      cout << "Const string is: ["
      << scSource << "]" << endl;
      cout << "Const string length is: ["
      << nLength << "]" << endl;
      cout << "Last character is: ["
      << scSource[nLength-1] << "]" << endl;
      cout << "Using length() returns: ["
      << scSource[nLength] << "]" << endl << endl << endl;

      string sSource("hijklmn");
      nLength = sSource.length();
      cout << "Non-const string is: ["
      << sSource << "]" << endl;
      cout << "Non-const string length is : ["
      << nLength << "]" << endl;
      cout << "Last character is: ["
      << sSource[nLength-1] << "]" << endl;
      cout << "Using length() returns: ["
      << sSource[nLength] << "]" << endl;

      return 0;
      }

      The output of this sample program is:


      Const string is: [abcdefg]
      Const string length is: [7]
      Last character is: [g]
      Using length() returns: [ ]

      Non-const string is: [hijklmn]
      Non-const string length is : [7]
      Last character is: [n]
      Using length() returns: [ ]

      As you can see, the string::operator[] is applicable using the length() function for both const strings and non-const strings - unlike specified in the aforementioned paragraph.

      However, the results are unpredictable. In the output produced above using the Code::Blocks Integrated Development Environment and the gcc compiler, nothing was returned in both cases. This is probably why length()’s usage is not recommended.

  • Odgarig

    Hi alex.First of all I’m very thankful to you for your awesome tutorials.
    I have written program that changes all strings given by user in upper case to lower case.And I’m failed.Here is my code and I wish you could help with my problem.

    [#include<string>
    #include <iostream>

    int main()
    {
        using namespace std;
        string lwr ("abcdefgh");
        string upr ("ABCDEFGH");
        string Astring;
        cout << "Enter a string: ";
        cin >> Astring;
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 8; j++)
             if (Astring[i] = upr[j])
                {
                    Astring[i] = lwr[j];
                }
             else { }
                
        }
        cout << "String in lowercase: " << Astring;

        return (0);
    }]
    I wrote only for these a,b,c,d,e,f,g,h letters.If my input is like deF then my program’s output should be def.

    • Alex

      I’d write a function that takes a reference to a character and if that character is found in lwr, converts it to the corresponding character in upr.

      Then you could loop through Astring letter by letter and call the function on each letter.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter