I am trying to slice the last four characters off a character array, and I tried the method that Python uses without success;
char *charone = (char*)("I need the last four")
char *chartwo = charone[-4:]
cout << chartwo << endl;
I would want this code to return:
four
But C/C++ doesn't seem to be that easy...
Where could I find a simple alternative that will return the last four characters of one character array into another character array?
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.
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.
array slicing in c++:
array<char, 13> msg = {"Hello world!"};
array<char, 6> part = {"world"};
// this line generates no instructions and does not copy data
// It just tells the compiler how to interpret the bits
array<char, 5>& myslice = *reinterpret_cast<array<char,5>*>(&msg[6]);
// now they are the same length and we can compare them
if( myslice == part )
cout<< "huzzah";
This is just one of the emamples where slicing is usefull
I have made a small library which does this with compile-time bounds checks at https://github.com/Erikvv/array-slicing-cpp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With