I have a situation where I have a std::string, and I only need characters x to x + y, and I think it would speed it up quite 开发者_开发问答a bit if I instead could somehow do (char*)&string[x], but the problem is all my functions expect a NULL terminated string.
What can I do?
Thanks
Nothing nice can be done. The only trick I can think of is temporarily setting s[x+y+1]
to 0, pass &s[x]
, then restore the character. But you should resort to this ONLY if you are sure this will reasonably boost the performance and that boost is necessary
nothing (if the string you need is in the middle). the speed difference will be utterly trivial unless its being done A LOT (several millions)
Use:
string.c_str() + x;
This assumes your function takes a const char *
If you need actual 0-termination, you'll have to copy.
You have no choice here. You can't create a null-terminated substring without copying or modifying the original string.
You say you "think it would speed it up". Have you measured?
You could overwrite &string[x+y+1]
with a NUL, and pass &string[x]
to your functions. If you're going to need the whole string again afterward, you can save it for the duration, and restore it when needed.
精彩评论