Reputation: 54123
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
Upvotes: 0
Views: 123
Reputation: 490178
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.
Upvotes: 0
Reputation: 133024
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
Upvotes: 3
Reputation: 272517
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?
Upvotes: 0
Reputation: 50190
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)
Upvotes: 1
Reputation: 91270
Use:
string.c_str() + x;
This assumes your function takes a const char *
If you need actual 0-termination, you'll have to copy.
Upvotes: 0