Substring of char[] in c++
If you need only to read the data then t+i is what you want, alas you'll have to manage the length of your substring...
char *sub = t+i;
int len = j-i;
printf("%.*s\n",len,sub);
If you need to have a distinct copy of the substring, then you must copy.
If you are allowed to modify t
, you could set t[j]
to 0
and then use t + i
to get the substring.
If not, you are going to have to make a copy.
That said, why can't you just use std::string
and save yourself the headache?
char* substr(char* arr, int begin, int len)
{
char* res = new char[len + 1];
for (int i = 0; i < len; i++)
res[i] = *(arr + begin + i);
res[len] = 0;
return res;
}