Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Get substring from char* in C

Posted on 2015-02-08
4
Medium Priority
?
1,066 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 2000 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 35

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

Independent Software Vendors: 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

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
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…

636 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