Get the tail of a string in C
I have a string, like "100110000111001100010001100011001100100
" .
If I need to get the tail of this string, meanin开发者_StackOverflow中文版g everything but the first element, do I have to copy each char to the new array, starting from the second element (O(n)),
or is there a faster way to do this, like somehow magically shift pointers 1 place to the right or a built in function?
If you don't need to make any modifications to the string then you can just give the original pointer plus 1, otherwise you will need to copy.
You can just make a char* that points to the index you need.
char *p = "100110000111001100010001100011001100100";
char *tail = &p[1]; //&p[1] is the same as p+1
printf("p = %s\ntail = %s\n",p,tail);
Nothing magical about it. A pointer to a string, like a pointer to an array, is just the address of the first element.
Basic pointer arithmetic, take your existing pointer, increment it (p++
), and you have a pointer to the "tail" of your string.
精彩评论