beakr
beakr

Reputation: 5867

Pure C: trim all characters in a string after a word occurs

I have a character array in C that can have a value such as /path/example/abc. I want it so that any characters after the /path/example/ part get gobbled up, reallocating the string for its new size. Is there a standard function, or function you could write that can accomplish this? Perhaps this could be accomplished with a library like PCRE? Note: Pure, platform-independent C code would be appreciated.

Example:

int main()
{
    char str[100] = "I am a string";
    newStr = globbleAfter(str, "I am a");
    printf("%s\n", newStr); 
    return 0;
}

//=> "I am a"

Upvotes: 0

Views: 913

Answers (3)

109
109

Reputation: 147

@Wojtek Surowka Without checking for the pattern within the original string there might be an instance where the pattern is not contained in the original string. There is also an issue if the pattern is found at some offset within the string.

String = "bob is running"
Pattern1 = "frank"
Pattern2 = "is run"

@Guntram Blohm After you malloc when do you free the allocated memory?

if ((gobbled=malloc(len=((pos-string)+strlen(pos)+1)))==NULL)

This method relies on src being less than 260 characters. It will not alter the original string.

This function is incorrect

#define MAX_PATH 260
char* gobbleAfter(const char* src, const char* pattern)
{
  int len = strlen(pattern);
  int cpy_len;
  char[MAX_PATH] gobbled_string;
  char* pos = strstr(src, pattern);

  gobbled_string[0] = '\0';

  if(pos)//null check
  {
    cpy_len = (pos - string) + len + 1
    if(cpy_len <= MAX_PATH)
    {
      memcpy(gobbled_string, src, cpy_len);
    }
  }
  return gobbled_string;
}

if you don't mind changing the source

char* gobbleAfter(char* src, const char* pattern)
{
  char* gobbled_string = NULL;
  char* temp = strstr(src, pattern);
  if(temp)
  {
    gobbled_string = src;
    gobbled_string[temp - src + strlen(pattern)] = '\0';
  }
  return gobbled_string;
}

Upvotes: 0

Guntram Blohm
Guntram Blohm

Reputation: 9819

PRCE seems overkill for this. Just use strstr to find newStr within str. Example:

char *gobbleAfter(char *string, char *pattern) {
    int len;
    char *gobbled;
    char *pos=strstr(string, pattern);
    if (pos==NULL)
        return NULL;
    if ((gobbled=malloc(len=((pos-string)+strlen(pos)+1)))==NULL)
        return NULL; /* or maybe call an out of memory handler */
    memcpy(gobbled, string, len-2);
    gobbled[len-1]='\0';
    return gobbled;
}

Upvotes: 1

Wojtek Surowka
Wojtek Surowka

Reputation: 21003

Since functions like printf work on zero-terminated strings, it is enough to set the first not-needed character to zero. Something like str[strlen("I am a")] = 0. It modifies the original string though. And most importantly it is not safe - before setting to zero you should check if the length of your substring is not greater than the length of the original string.

Upvotes: 0

Related Questions