Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 732
  • Last Modified:

C string manipulation

Hi,
I am trying to extract a substring from a C string(character array).  Specifically, I am trying to extract the substring up to the first delimiter '|'.
Example: if i have the string 'abcd| efg'
I want to get the C string 'abcd' and return it.
Thanks.
0
aomega
Asked:
aomega
  • 4
  • 2
1 Solution
 
sunnycoderCommented:
char * string = "abcd| efg";
char buffer[10];

temp = strchr ( string, '|' );
strncpy ( buffer, string, temp - string );
buffer[temp - string] = 0;

now buffer has the required string
0
 
sunnycoderCommented:
another alternative is to use strtok

temp = strtok ( string, "|" );
return temp;

beware, strtok will modify your original string unlike strchr
0
 
aomegaAuthor Commented:
SunnyCoder,
The 5th line : strncpy ( buffer, string, temp - string ) has temp-string as the third parameter.  I am not familiar with subtracting character arrays. What exactly does this accomplish?  thanks.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
sunnycoderCommented:
it is not subtracting arrays but pointer .. pointers are nothing but addresses (numbers)
e.g.

string starts at 1000

a  1000
b  1001
c   1002
d  1003
|   1004
e  1005
f   1006
g  1007

after strchr string = 1000 and temp = 1004
1004 - 1000 = 4 .. so it will copy 4 chars
0
 
aomegaAuthor Commented:
thanks for the explanation.
I have pretty much the same as your first example except char *string being passed as a parameter to the function.

char *getKey(char *line){
static char buffer[1000];
char *temp;

temp = strchr(line, '|');
strncpy(buffer, line, temp-line);
buffer[temp-line] = '\0';
return(buffer);
}

I am gettting a segfault at the line strncpy.  I am not quite sure why that is in this case.
0
 
sunnycoderCommented:
runs perfectly
... the segfault may be at some other line ... also you are not performing any error checking ... what if strchr returns NULL ?

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

char * getkey ( char * a )
{
        static char buffer[100];

        char * temp;

        temp = strchr (a, '|' );

        strncpy ( buffer, a, temp - a );

        buffer [ temp - a ] = 0;

        return buffer;
}

int main ()
{
        char * a = "abcd|efg";

        char * t;

        t = getkey ( a );

        printf ( "%s\n", t );
}
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now