Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String slicing in C++

Tags:

c++

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?

like image 446
daxvena Avatar asked Feb 19 '11 02:02

daxvena


3 Answers

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.

like image 91
Nikolai Fetissov Avatar answered Nov 13 '22 09:11

Nikolai Fetissov


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.

like image 45
Jeremiah Willcock Avatar answered Nov 13 '22 10:11

Jeremiah Willcock


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

like image 32
Erik van Velzen Avatar answered Nov 13 '22 09:11

Erik van Velzen