Solved

Get substring from char* in C

Posted on 2015-02-08
4
529 Views
Last Modified: 2015-02-14
Hi Experts,

I need to get the left substring from char* in C.
E.g.

char* str = "<1.2.3.4:4747>;+instance=45;+gks=uuu

I need to get the following:

char* substr = "<1.2.3.4:4747>

Thanks for the help
0
Comment
Question by:bachra04
  • 2
4 Comments
 
LVL 86

Expert Comment

by:jkr
Comment Utility
'strtok()' (http://www.cplusplus.com/reference/cstring/strtok/) can do that for youm especially if you later need other parts of that source string as well:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="<1.2.3.4:4747>;+instance=45;+gks=uuu.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str,";");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

Open in new window


If you really only need the part up to the fist semicolon, then 'strchr()' (http://www.cplusplus.com/reference/cstring/strchr/) and a copy function will do, e.g.

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "<1.2.3.4:4747>;+instance=45;+gks=uuu.";
  char * pch;
  printf ("Looking for the ';' character in \"%s\"...\n",str);
  pch=strchr(str,';');
  while (pch!=NULL)
  {
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,';');
  }
  return 0;
}

Open in new window


or specifically for your case:

#include <stdio.h>
#include <string.h>

int extract_string (const char* pIn, char* pOut, size_t szOutBuf)
{
  int result = 0;
  char str[] = "<1.2.3.4:4747>;+instance=45;+gks=uuu.";
  char * p = NULL;
  p = strchr(pIn,';');
  if (p != NULL)
  {
    size_t count = p - pIn;
   
    if ( szOutBuf <= offs) return -1; // output buffer too small

    strcpyn(pOut,pIn,count);
    pOut[count] = '\0'; // terminate it

    result = count;
  }
  return result;
}

Open in new window

0
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
Comment Utility
BTW, here'sa more general method to extract substrings:

http://www.programmingsimplified.com/c/source-code/c-substring

#include <stdio.h>
#include <malloc.h>
 
char* substring(char*, int, int);
 
int main() 
{
   char string[100], *pointer;
   int position, length;
 
   printf("Enter a string\n");
   gets(string);
 
   printf("Enter the position and length of substring\n");
   scanf("%d%d",&position, &length);
 
   pointer = substring( string, position, length);
 
   printf("Required substring is \"%s\"\n", pointer);
 
   free(pointer);
 
   return 0;
}
 
/*C substring function: It returns a pointer to the substring */
 
char *substring(char *string, int position, int length) 
{
   char *pointer;
   int c;
 
   pointer = malloc(length+1);
 
   if (pointer == NULL)
   {
      printf("Unable to allocate memory.\n");
      exit(EXIT_FAILURE);
   }
 
   for (c = 0 ; c < position -1 ; c++) 
      string++; 
 
   for (c = 0 ; c < length ; c++)
   {
      *(pointer+c) = *string;      
      string++;   
   }
 
   *(pointer+c) = '\0';
 
   return pointer;
}

Open in new window

0
 
LVL 32

Expert Comment

by:sarabande
Comment Utility
/*C substring function: It returns a pointer to the substring */
you may consider to use the following substring function instead:

#include <string.h>

const char * substring(char sub[], int sizsub, const char * input, int offset, int lensub) 
{
    int len;
    if (sub == 0 || input == 0 || sizsub <= 0 || offset < 0 || lensub < 0)
        return 0;
    len = strlen(input);
    sub[0] = '\0';
    if (offset < len)
    {
        if (offset + lensub > len)
            lensub = len - offset;
        if (lensub >= sizsub)
            lensub = sizsub-1;
        strncpy(sub, input+offset, lensub);
        sub[lensub] = '\0';
    }
    return sub;
}

Open in new window


the function is safe regarding null pointers or wrong input arguments.

the function wants you to supply a buffer for the substring rather than creating a buffer on the heap. that way you can fill variables without copy and free of the returned pointer.

you also can get a substring at end of input string without needing to pass the exact length of the substring to extract..

Sara
0
 
LVL 2

Author Comment

by:bachra04
Comment Utility
Thanks Sara
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now