Get the last element of a std::string

后端 未结 4 1009
自闭症患者
自闭症患者 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: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!

提交回复
热议问题