Solved

Get substring from char* in C

Posted on 2015-02-08
4
696 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
ID: 40597294
'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
ID: 40597301
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 33

Expert Comment

by:sarabande
ID: 40607671
/*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
ID: 40609798
Thanks Sara
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

808 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