0

In Python and C#, we need to place a negative index to get last value.

In C++, I don't know how to do it. I tried the same way to do it but it didn't work out.

Example

string str = "get last space "
cout << str[-1];

In this example, I should get null value because there's a tailing space in the string. How can I do this?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Ishk
  • 21
  • 4
  • 4
    Remember that for any string (or container in general) the valid range of indexes is `0` to `container.length() - 1` (inclusive). When you use `-1` as index, you get the character "before" the string, which is out of bounds and leads to *undefined behavior*. – Some programmer dude Oct 19 '20 at 02:49
  • 3
    First, in C++ you can't get last element of array/string/etc referring to -1st index. Use `str[str.length() - 1]` or `str.back()`. Second, you won't get null, you'll get space character. – fas Oct 19 '20 at 02:50
  • 3
    And generally speaking you can't use constructs or expressions possible in other languages. They seldom (if ever) work, or at least not work the same way. Different language are different (much like spoken and written languages differ). – Some programmer dude Oct 19 '20 at 02:51
  • To find the length of a string, you can use [`std::string::length`](https://en.cppreference.com/w/cpp/string/basic_string/size). Therefore, to get the last character of a string, if you are sure that the length is at least one, you can write `str[str.length()-1]`. – Andreas Wenzel Oct 19 '20 at 02:51
  • 4
    Perhaps you need to spend some time to actually *learn* C++? Do you have [some decent books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read? Are you taking classes? – Some programmer dude Oct 19 '20 at 02:52

5 Answers5

3
cout << str[str.length() - 1];

str.length()will return the number of chars in this string, and to get the char at the end of str, you should use the index of the end char, which is 1 less than str length, since 0 is the first index

2

you can use back() method in string class :

string str = "get last space ";
cout << str.back();

its return char& to last character in string

aziz k'h
  • 775
  • 6
  • 11
0

Since you are using std::string, you can use the method std.back();.

cout << str.back();

This will get the last character of the string as you wish.

BendedWills
  • 99
  • 2
  • 10
0

Since no one mentioned str.back() is UB if str is empty, I'd like to elaborate on it.

std::cout << str.back(); // Trigger UB if str.emtpy() == true

The better form is as following:

if(str.empty() == false){
   std::cout << str.back();
}

Since str.back() is equivalent to str[str.length()-1], they both have UB when str is empty.

Louis Go
  • 2,213
  • 2
  • 16
  • 29
0

You can also use the str.end() iterator

string str = "get last space ";
cout << *(str.end()-1);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31