Comparing strings from within strings

R

Rick

Hi,

I need to extract some data from a string being passed. I was wondering
what would be the best way of doing this. For example, I have two
strings: "SWITCH1CLOSE" and "GATE1OPEN"

I need to take out the SWITCH part of out of the string, the "1" and the
"close". Similarly, I need to take out GATE, 1 and open from the second
string. Should I use the "strstr" function for comparing the substrings
GATE, CLOSE, OPEN etc? I can't use the tokenizing function here so I'm
not sure what would be the best way of doing this. Any suggestions would
be great! Thanks


Rick
 
R

Richard Heathfield

Rick said:
Hi,

I need to extract some data from a string being passed. I was wondering
what would be the best way of doing this. For example, I have two
strings: "SWITCH1CLOSE" and "GATE1OPEN"

I need to take out the SWITCH part of out of the string, the "1" and the
"close". Similarly, I need to take out GATE, 1 and open from the second
string. Should I use the "strstr" function for comparing the substrings
GATE, CLOSE, OPEN etc? I can't use the tokenizing function here so I'm
not sure what would be the best way of doing this. Any suggestions would
be great! Thanks

Yes, strstr is fine. You might not want to search from the beginning each
time, though. For example, you might want to find "GATE" and "OPEN" in your
second example. You can use a pointer to keep track of how far "into" the
string you are, and strstr to compare from that point.

char s[] = "SOMERANDOMLEADINGTEXTGATE1OPEN";
char *p = strstr(s, "GATE");

if(p != NULL)
{
/* do whatever it was you needed to do at this point, then ... */
p += strlen("GATE"); /* skip past characters of "GATE", so p now points to
the '1' character. */
p = strstr(p, "OPEN"); /* off to the next match... */


If you want to jump forward to a particular /character/, you might also find
strchr useful.
 
R

Rick

Thanks a lot Richard! One question though, is there a Standard C
function that converts lower case characters to upper case? Thanks

Rick
 
I

Irrwahn Grausewitz

Rick said:
Thanks a lot Richard! One question though, is there a Standard C
function that converts lower case characters to upper case? Thanks

Lookup toupper in your library reference.

Regards
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top