| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | C |
Hi Bob
BL> How the bloody hell do I read part of a string in C?
BL>
BL> I've got 3:711/934.12 and I want to read the 711. How do I do it?
BL>
BL> In Pascal I'd use COPY("3:711/934.12",3,3); but how do
you pick a
BL> string out of a string in C?
Most of the string handling functions in C start with str. Check
the library reference.
Use a pointer (to char) to point to the first char of the
substring you want to pull out, then use strncpy() to get it out.
Because strncpy() doesn't always guarantee to null terminate its
result, we do this ourselves afterwards.
char dest[4];
char *source = "3:711/934.12";
char *p;
p = source + 2;
strncpy (dest, p, 3);
dest[3] = "\0";
You could also write
source += 2; /* point "source" at the 3rd char */
strncpy (dest, source, 3);
dest[3] = "\0";
because source is just a pointer to char, but you can start to lose
track of where the original string started if you're not careful.
The function strtok() is probably better here. It walks its way
through a string, replacing the delimiter characters you supply in
the 2nd parameter with nulls, splitting the string up into
null-terminated stringlets (tokens). It will work on
"33:71/9034.45", where the above strncpy() demo won't. Note that it
modifies the source string.
This demo (copied pretty well straight from the library reference)
doesn't explicitly find the 2nd substring, it just prints the lot:
p = strtok (source, "/:."); /* find 1st stringlet */
while (p) /* strtok will return NULL when finished */
{
printf ("%s\n", p);
p = strtok (NULL, "/:."); /* find the next stringlet */
}
That's the general case, which assumes that you don't know what
order the delimiters are going to appear, and that you don't know
how many tokens there will be. If you already know the form of the
string, use
p = strtok (source, ":"); /* find 1st token */
cout << p << endl; /* print it */
p = strtok (NULL, "/"); /* find next token */
strcpy (dest, p); /*copy it out. p is already null-terminated*/
cout << p << endl; /* etc etc */
p = strtok (NULL, ".");
cout << p << endl;
(a bit of gratuitous C++ thrown in cos I like printf only a bit
more than scanf...)
Cheers
--- PPoint 1.80
* Origin: Silicon Heaven (3:711/934.16)SEEN-BY: 711/934 @PATH: 711/934 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.