Get last X characters from string of Y length

Suppose I have a variable of string object type. The length of the string is Y. I would like to retrieve the last X characters from this string. How can this be done?

EDIT: I just had an idea! Get the length first and subtract from there! Any better alternatives?

No, this is your answer.

Just remember, a string has a "terminating" character at the end. So you want the last X+1 really.

Johnny010:
No, this is your answer.

Just remember, a string has a "terminating" character at the end. So you want the last X+1 really.

Valid if I am not using String object. However, I am using String object.

Here is my own solution;

String testStr;
testStr.substring(Y-X);

The usual solution is “don’t use the String object type”. Particularly not if you are doing things like this. the substring string method creates a new object on the heap, which has got to be cleaned up etc etc.

PaulMurrayCbr:
The usual solution is "don't use the String object type". Particularly not if you are doing things like this. the substring string method creates a new object on the heap, which has got to be cleaned up etc etc.

Why is String object bad? Does the new object on the heap needs to be manually cleaned up by code?

Why is String object bad?

Below are the String functions which have some good examples. You could use your approach to get the length of the String, subtract the number of characters of interest on the end of the String, then use the substring() function to capture the characters of interest.

Why is String object bad?

The String class has a lot of useful stuff in it, but its two biggest drawbacks are: 1) it eats up more memory than an equivalent program using c strings, and 2) it can fragment memory. In the code below, the String class version uses 3512 bytes while the c string version uses 1870 bytes. When you're working with a few nano-acres of memory, the cost of using Strings is pretty steep.

void setup() {

  Serial.begin(9600);
  int len;
  
 // String testStr = "This is a test";  // This version takes 3512 bytes
 // len = testStr.length();
 // Serial.println(testStr.substring(len - 3, len));

  char testStr[] = "This is a test";    // This version takes 1870 bytes
  len = strlen(testStr);
  Serial.println(&testStr[len - 3]);
 
}

void loop() {
}