String slicing in C++
Try:
int len = strlen(charone);
char *chartwo = charone + (len < 4 ? 0 : len - 4);
In C++, you can replace that with:
char* chartwo = charone + (std::max)(strlen(charone), 4) - 4;
The code uses a special property of C strings that only works for chopping off the beginning of a string.
First, let's remove the deprecated conversion:
char const *charone = "I need the last four";
Arrays are not first-class values in C++, and they don't support slicing. However, just as the above charone points to the first item in the array, you can point to any other item. Pointers are used with chars to make C-style strings: the pointed-to char up until a null char is the contents of the string. Because the characters you want are at the end of the current (charone) string, you can point at the "f":
char const *chartwo = charone + 16;
Or, to handle arbitrary string values:
char const *charone = "from this arbitrary string value, I need the last four";
int charone_len = strlen(charone);
assert(charone_len >= 4); // Or other error-checking.
char const *chartwo = charone + charone_len - 4;
Or, because you're using C++:
std::string one = "from this arbitrary string value, I need the last four";
assert(one.size() >= 4); // Or other error-checking, since one.size() - 4
// might underflow (size_type is unsigned).
std::string two = one.substr(one.size() - 4);
// To mimic Python's [-4:] meaning "up to the last four":
std::string three = one.substr(one.size() < 4 ? 0 : one.size() - 4);
// E.g. if one == "ab", then three == "ab".
In particular, note that std::string gives you distinct values, so modifying either string doesn't modify the other as happens with pointers.
C++ and Python are very different. C++ does not have built-in Python-like string facilities, but its Standard Template Library has a handy std::string
type, which you should look into.