0

If string is just an array of chars, then is it considered bad coding to directly access an index of a string? for example...

 string test = "Hello"; 
 cout << text.[0];

 int lenOfTest = (int)test.length();
 for(int i = 0; i < lenOfTest; i++ ){
   cout << test[i];
 }
2
  • 1
    This is fine, except for text.[0], I guess that is some sort of typo Commented Apr 5, 2014 at 0:40
  • 1
    A std::string is not just an array of characters. It's a standard class, which overloads [] to access the elements of the string. Commented Apr 5, 2014 at 0:41

2 Answers 2

3

A std::string is not a simple array of char, although it is a container of char, and yes, you can access each of its elements normally. Just don't use the point before the open [ like you did in your second line.

Sign up to request clarification or add additional context in comments.

4 Comments

The std::string does wrap an array of char though, which you have full access to.
@MattMcNabb, one would actually hope you don't have full access to the underlying buffer. If you look at libc++, for instance, there are two buffers, only one of which is actually in use for a given instance - I would hope users don't get to muck with either fully and directly
You can get it via &s[0]. To be clear I should say "full access to the contents of", I guess; you can't reallocate it .
you also shouldn't write to the memory pointed to by &s[0] (nor c_str() or data()...) because it's UB.
2

I don't think it is a bad practice to access a char element using the operator[], however keep in mind that accessing a character like this will not raise an exception in case a invalide position is being used. To raise an exception, use the string::at.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.