Get the last element of a std::string

后端 未结 4 1004
自闭症患者
自闭症患者 2020-12-08 03:38

I was wondering if there\'s an abbreviation or a more elegant way of getting the last character of a string like in:

char lastChar = myString.at( myString.le         


        
相关标签:
4条回答
  • 2020-12-08 04:05

    You probably want to check the length of the string first and do something like this:

    if (!myStr.empty())
    {
        char lastChar = *myStr.rbegin();
    }
    
    0 讨论(0)
  • 2020-12-08 04:07

    *(myString.end() - 1) maybe? That's not exactly elegant either.

    A python-esque myString.at(-1) would be asking too much of an already-bloated class.

    0 讨论(0)
  • 2020-12-08 04:24

    You could write a function template back that delegates to the member function for ordinary containers and a normal function that implements the missing functionality for strings:

    template <typename C>
    typename C::reference back(C& container)
    {
        return container.back();
    }
    
    template <typename C>
    typename C::const_reference back(const C& container)
    {
        return container.back();
    }
    
    char& back(std::string& str)
    {
        return *(str.end() - 1);
    }
    
    char back(const std::string& str)
    {
        return *(str.end() - 1);
    }
    

    Then you can just say back(foo) without worrying whether foo is a string or a vector.

    0 讨论(0)
  • 2020-12-08 04:25

    In C++11 and beyond, you can use the back member function:

    char ch = myStr.back();
    

    In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin:

    char ch = *myStr.rbegin();
    

    In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题