user7143217
user7143217

Reputation:

Remove first few characters from a string

I need to remove the first 3 characters from an array without any libraries. How would I go about doing this? I know that I can use memmove but I'm working on a system without the standard library, also memmove is for pointers. With memmove I can do this:

void chopN(char *str, size_t n)
{
    assert(n != 0 && str != 0);
    size_t len = strlen(str);
    if (n > len)
        return;  // Or: n = len;
    memmove(str, str+n, len - n + 1);
}

But could I remove characters from an array without memmove or any other standard library functions?

Upvotes: 1

Views: 3757

Answers (5)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

Here is a function that does not use standard C string functions. n can be less then or equal to strlen( s ). Otherwise the function does nothing.

#include <stdio.h>

char * chopN( char *s, size_t n )
{
    char *src = s;

    while ( *src && n ) --n, ++src;

    if ( n == 0 && src != s )
    {
        for ( char *dst = s; (  *dst++ = *src++ ); );
    }

    return s;
}   

int main(void) 
{
    char s[] = "Hello, World";

    puts( s );
    puts( chopN( s, 7 ) );

    return 0;
}

The program output is

Hello, World
World

If you want that in case when n is greater than strlen( s ) all characters were removed then it is enough to substituted the if statement

if ( n == 0 && src != s )

for this one

if ( src != s )

Upvotes: 1

Guilherme Garcia da Rosa
Guilherme Garcia da Rosa

Reputation: 1030

You don't need to pass the "amount" of characters as a parameter, you can search for '\0':

void chopN(char *str, size_t n){
    char *aux;
    int i=0,j=0;
    while(str[i]!='\0'){
        if(i>n+1){
            aux[j++]=str[i++];
        }else i++;
    }
    aux[j]='\0';
    str = aux;
}

Upvotes: 0

chux
chux

Reputation: 153358

Hmmm: 2 simple while loops should do it.

Some untested code to give you an idea.

void chopN(char *str, size_t n) {
  char *dest = str;

  // find beginning watching out for rump `str`
  while (*str && n--) {
    str++;
  }

  // Copy byte by byte
  while (*src) {
    *dest++ = *src++;
  }

  *dest = '\0';
}

Could add a if (n==0) short-cut if desired.

Upvotes: 2

Petr Skocik
Petr Skocik

Reputation: 60058

Simply start at the new start (str+n) and copy to the old start char by char until you reach the end of the string:

char *str1;
for(str1 = str+n; *str1; *str++=*str1++) 
   ;
*str = 0;

If you want something more powerful, you can e.g., steal a memmove implementation from http://git.musl-libc.org/cgit/musl/tree/src/string/memmove.c (it basically does the same thing, except with some performance tweaks and a decision on which way (left/right) the move goes).

Upvotes: 0

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

As long as you know the string is at least 3 characters long, you can simply use str + 3.

Upvotes: 2

Related Questions