Kevin Williams
Kevin Williams

Reputation: 3

Get certain parts out of a string using C

Evening everyone hope on of you gurus can help. I am trying to find the answer to this issue I need to read the data out of the string below by searching the tags. i.e IZTAG UKPART etc however the code I am using is no good as it only stores the 1st part of it for example UKPART = 12999 and misses out the -0112. Is there a better way to search strings ?

UPDATE SO FAR.

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

int main ()  
{  
    // in my application this comes from the handle and readfile 
    char buffer[255]="TEST999.UKPART=12999-0112...ISUE-125" ;     
    // 
    int i;  
    int codes[256];   
    char *pos = buffer;   
    size_t current = 0;   
    //   
       char buffer2[255];
   if ((pos=strstr(pos, "UKPART")) != NULL) {   
        strcpy (buffer2, pos); // buffer2 <= "UKPART=12999-0112...ISUE-125"
   }

        printf("%s\n", buffer2);  
    system("pause"); 
    return 0;  
}  

NOW WORKS BUT RETURN WHOLE STRING AS OUTPUT I NEED TO JUST RETURN UKPART FOR EXAMPLE THANKS SO FAR :-)

Upvotes: 0

Views: 70

Answers (1)

paulsm4
paulsm4

Reputation: 121799

  1. strstr() is absolutely the right way to search for the substring. Cool :)

  2. It sounds like you want something different from "sscanf()" to copy the substring.

Q: Why not just use "strcpy ()" instead?

EXAMPLE:
   char buffer[255]="IZTAG-12345...UKPART=12999-0112...ISUE-125" ;     
   char buffer2[255];
   if ((pos=strstr(pos, "UKPART")) != NULL) {   
        strcpy (buffer2, pos); // buffer2 <= "UKPART=12999-0112...ISUE-125"

Upvotes: 2

Related Questions