Search code examples
c++arraysclassstringpointer-arithmetic

Is pointer arithmetic possible with C++ string class?


After programming a little in C I decided to jump right into C++. At first I was pleased with the presence of the string class and being able to treat strings as whole units instead of arrays of characters. But I soon found that the C-style strings had the advantage of letting the program move through it character by character, using pointer arithmetic, and carry out a desired logical operation.

I have now found myself in a situation that requires this but the compiler tells me it is unable to convert from type string to the C-style strings. So I was wondering, is there a way to use pointer arithmetic to reference single characters or to pass arguments to a function as the address of the first character while still using the string class without having to create arrays of characters or do I just want to have my cake and eat it too?


Solution

  • string characters can be accessed by index, pointers, and through the use of iterators.

    if you wanted to use iterators, you could make a function that checks whether a string has a space in it or not:

    bool spacecheck(const string& s)
    {
        string::const_iterator iter = s.begin();
        while(iter != s.end()){
            if (isspace(*iter))
                return true;
            else
                ++iter;
        }
    }
    

    At the beginning of the function, I initialized an iterator to the beginning of the string s by using the .begin() function, which in this case returns an iterator to the first character in a string. In the while function, the condition is that iter != s.end(). In this case end() returns in iterator referring to the element after the last character of the string. In the body, (*iter), which is the value pointed to by iter, is sent to the function isspace(), which checks if a character is a space. If it fails, iter is incremented, which makes iter point to the next element of the string.

    I am learning c++ myself and by writing all of this stuff out it has helped my own understanding some. I hope I did not offend you if this all seemed very simple to you, I was just trying to be concise.

    I am currently learning from Accelerated c++ and I could not recommend it highly enough!