What is the less expensive way to remove a char from the start of a string in C?

138 views Asked by At

I have to create a very inexpensive algorithm (processor and memory) to remove the first char from a string (char array) in C.

I'm currently using:

char *newvalue = strdup(value+1);
free(value);
value = newvalue;

But I want to know if there is some less expensive way to do that. The string value is dynamically allocated.

3

There are 3 answers

1
timrau On BEST ANSWER

Reuse the original array. May or may not be faster, depend on the relative speed of memory (de)allocation and copy.

int size = strlen(value);
if (size > 0) memmove(value, value+1, size);
0
unwind On

Since heap calls will be quite expensive, the obvious optimization is to avoid them.

If you need to do this often, you could probably come up with some simple wrapper around the bare pointer that can express this.

Something like:

typedef struct {
  const char *chars;
  size_t offset;
} mystring;

Then you'd need to devise an API to convert a mystring * into a character pointer, by adding the offset:

const char * mystring_get(const mystring *ms)
{
  return ms->chars + ms->offset;
}

and of course a function to create a suffix where the 1st character is removed:

mystring mystring_tail(const mystring *ms)
{
  const mystring suffix = { ms->chars, ms->offset + 1};

  return suffix;
}

note that mystring_tail() returns the new string structure by value, to avoid heap allocations.

3
Olotiar On

value+1 is a char* that represent the string with the first character removed. It is the less expensive way to obtain such a string..

You'll have to be careful when freeing memory though to make sure to free the original pointer and not the shifted one.