Solved

Get substring from char* in C

Posted on 2015-02-08
4
876 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 34

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

691 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