473,625 Members | 2,853 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Breaking strings apart

I'm working on a prompt style thing and I need a way to pass arguments
to commands within my program. For example:

::hello -v -r -n

If this is entered as one input string, can I (in any simple way) break
it apart so I have something like:

str[0] = "hello"
str[1] = "-v"
str[2] = "-r"
str[3] = "-n"

This way say I had a command connect I could do this:

::connect 0.0.0.0 0

And later use this to connect to the internet by saying okay str[0] =
"connect" so connect str[1] = "0.0.0.0" so connect to 0.0.0.0 str[2] =
"0" so connect to 0.0.0.0 on port 0. Thanks.
Nori

P.S. My question is not related to network programing it was simply an
example. I am well aware how to code this on my own I just need some
way to get input from the user properly.

May 24 '06 #1
7 3268

no*********@gma il.com wrote:
::hello -v -r -n

If this is entered as one input string, can I (in any simple way) break
it apart so I have something like:

str[0] = "hello"
str[1] = "-v"
str[2] = "-r"
str[3] = "-n"


Sure, assuming str is defined appropriately, say as a char **.
Assuming your command line is space-delimited, and you feel adequate to
the task, strtok() can do what you want.

May 24 '06 #2
no*********@gma il.com wrote:

I'm working on a prompt style thing and I need a way to pass arguments
to commands within my program. For example:

::hello -v -r -n I just need some
way to get input from the user properly.


/* BEGIN pops_device.c */
/*
** If rc equals 0, then an empty line was entered
** and the array contains garbage.
** If rc equals EOF, then the end of file was reached.
** If rc equals 1, then there is a string in array.
** Up to LENGTH number of characters are read
** from a line of a text file or stream.
** If the line is longer than LENGTH,
** then the extra characters are discarded.
*/
#include <stdio.h>

#define LENGTH 80
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
int rc;
char array[LENGTH + 1];

puts("The LENGTH macro is " xstr(LENGTH));
fputs("Enter a string with spaces:", stdout);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getchar();
}
while (rc == 1) {
printf("Your string is:%s\n\n"
"Hit the Enter key to end,\nor enter "
"another string to continue:", array);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getchar();
}
if (rc == 0) {
*array = '\0';
}
}
return 0;
}

/* END pops_device.c */
--
pete
May 24 '06 #3

no*********@gma il.com wrote:
I'm working on a prompt style thing and I need a way to pass arguments
to commands within my program. For example:

::hello -v -r -n

If this is entered as one input string, can I (in any simple way) break
it apart so I have something like:

str[0] = "hello"
str[1] = "-v"
str[2] = "-r"
str[3] = "-n"

7.21.5.8 p 1 & 2

#include <string.h>

char *strtok(char * restrict s1, const char * restrict s2);

A sequence of calls to the strtok function breaks the string
pointed to by s1 into a sequence of tokens, each of which
is delimited by a character from the string pointed to
by s2. The first call in the sequence has a non-null first
argument; subsequent calls in the sequence have a null first
argument. The separator string pointed to by s2 may be
different from call to call.

Look it up in your manual or the Standard.

May 24 '06 #4
"no*********@gm ail.com" wrote:

I'm working on a prompt style thing and I need a way to pass
arguments to commands within my program. For example:

::hello -v -r -n

If this is entered as one input string, can I (in any simple way)
break it apart so I have something like:

str[0] = "hello"
str[1] = "-v"
str[2] = "-r"
str[3] = "-n"

.... snip ...

Try the following. You can easily create the toksplit.h file for
yourself. Another possibility is the standard function strtok,
which has some nuisance characteristics .

/* ------- file toksplit.c ----------*/
#include "toksplit.h "

/* copy over the next token from an input string, after
skipping leading blanks (or other whitespace?). The
token is terminated by the first appearance of tokchar,
or by the end of the source string.

The caller must supply sufficient space in token to
receive any token, Otherwise tokens will be truncated.

Returns: a pointer past the terminating tokchar.

This will happily return an infinity of empty tokens if
called with src pointing to the end of a string. Tokens
will never include a copy of tokchar.

A better name would be "strtkn", except that is reserved
for the system namespace. Change to that at your risk.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
*/

const char *toksplit(const char *src, /* Source of tokens */
char tokchar, /* token delimiting char */
char *token, /* receiver of parsed token */
size_t lgh) /* length token can receive */
/* not including final '\0' */
{
if (src) {
while (' ' == *src) *src++;

while (*src && (tokchar != *src)) {
if (lgh) {
*token++ = *src;
--lgh;
}
src++;
}
if (*src && (tokchar == *src)) src++;
}
*token = '\0';
return src;
} /* toksplit */

#ifdef TESTING
#include <stdio.h>

#define ABRsize 6 /* length of acceptable token abbreviations */

int main(void)
{
char teststring[] = "This is a test, ,, abbrev, more";

const char *t, *s = teststring;
int i;
char token[ABRsize + 1];

puts(teststring );
t = s;
for (i = 0; i < 4; i++) {
t = toksplit(t, ',', token, ABRsize);
putchar(i + '1'); putchar(':');
puts(token);
}

puts("\nHow to detect 'no more tokens'");
t = s; i = 0;
while (*t) {
t = toksplit(t, ',', token, 3);
putchar(i + '1'); putchar(':');
puts(token);
i++;
}

puts("\nUsing blanks as token delimiters");
t = s; i = 0;
while (*t) {
t = toksplit(t, ' ', token, ABRsize);
putchar(i + '1'); putchar(':');
puts(token);
i++;
}
return 0;
} /* main */

#endif
/* ------- end file toksplit.c ----------*/

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
May 24 '06 #5

Vladimir Oka wrote:
no*********@gma il.com wrote:
I'm working on a prompt style thing and I need a way to pass arguments
to commands within my program. For example:

::hello -v -r -n

If this is entered as one input string, can I (in any simple way) break
it apart so I have something like:

str[0] = "hello"
str[1] = "-v"
str[2] = "-r"
str[3] = "-n"

7.21.5.8 p 1 & 2

#include <string.h>

char *strtok(char * restrict s1, const char * restrict s2);

A sequence of calls to the strtok function breaks the string
pointed to by s1 into a sequence of tokens, each of which
is delimited by a character from the string pointed to
by s2. The first call in the sequence has a non-null first
argument; subsequent calls in the sequence have a null first
argument. The separator string pointed to by s2 may be
different from call to call.

Look it up in your manual or the Standard.


If you don't need to stick to standard functions, have look at
`getopt()`. Googling for it should take you to someplace useful. I know
it's part of GNU C Library, but it should be available more widely as
well.

May 24 '06 #6
I guess I don't understand what would go in the toksplit.h file or even
why it would be nessisary: it worked fine without it. If you could
elaborate it would be much apreciated. Also thanks really good
example.
Nori

CBFalconer wrote:
"no*********@gm ail.com" wrote:

I'm working on a prompt style thing and I need a way to pass
arguments to commands within my program. For example:

::hello -v -r -n

If this is entered as one input string, can I (in any simple way)
break it apart so I have something like:

str[0] = "hello"
str[1] = "-v"
str[2] = "-r"
str[3] = "-n"

... snip ...

Try the following. You can easily create the toksplit.h file for
yourself. Another possibility is the standard function strtok,
which has some nuisance characteristics .

/* ------- file toksplit.c ----------*/
#include "toksplit.h "

/* copy over the next token from an input string, after
skipping leading blanks (or other whitespace?). The
token is terminated by the first appearance of tokchar,
or by the end of the source string.

The caller must supply sufficient space in token to
receive any token, Otherwise tokens will be truncated.

Returns: a pointer past the terminating tokchar.

This will happily return an infinity of empty tokens if
called with src pointing to the end of a string. Tokens
will never include a copy of tokchar.

A better name would be "strtkn", except that is reserved
for the system namespace. Change to that at your risk.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
*/

const char *toksplit(const char *src, /* Source of tokens */
char tokchar, /* token delimiting char */
char *token, /* receiver of parsed token */
size_t lgh) /* length token can receive */
/* not including final '\0' */
{
if (src) {
while (' ' == *src) *src++;

while (*src && (tokchar != *src)) {
if (lgh) {
*token++ = *src;
--lgh;
}
src++;
}
if (*src && (tokchar == *src)) src++;
}
*token = '\0';
return src;
} /* toksplit */

#ifdef TESTING
#include <stdio.h>

#define ABRsize 6 /* length of acceptable token abbreviations */

int main(void)
{
char teststring[] = "This is a test, ,, abbrev, more";

const char *t, *s = teststring;
int i;
char token[ABRsize + 1];

puts(teststring );
t = s;
for (i = 0; i < 4; i++) {
t = toksplit(t, ',', token, ABRsize);
putchar(i + '1'); putchar(':');
puts(token);
}

puts("\nHow to detect 'no more tokens'");
t = s; i = 0;
while (*t) {
t = toksplit(t, ',', token, 3);
putchar(i + '1'); putchar(':');
puts(token);
i++;
}

puts("\nUsing blanks as token delimiters");
t = s; i = 0;
while (*t) {
t = toksplit(t, ' ', token, ABRsize);
putchar(i + '1'); putchar(':');
puts(token);
i++;
}
return 0;
} /* main */

#endif
/* ------- end file toksplit.c ----------*/

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>


May 25 '06 #7
*** top-posting fixed ***
"no*********@gm ail.com" wrote:
CBFalconer wrote:
"no*********@gm ail.com" wrote:

I'm working on a prompt style thing and I need a way to pass
arguments to commands within my program. For example:

::hello -v -r -n

If this is entered as one input string, can I (in any simple way)
break it apart so I have something like:

str[0] = "hello"
str[1] = "-v"
str[2] = "-r"
str[3] = "-n"

... snip ...

Try the following. You can easily create the toksplit.h file for
yourself. Another possibility is the standard function strtok,
which has some nuisance characteristics .

/* ------- file toksplit.c ----------*/
#include "toksplit.h "

/* copy over the next token from an input string, after
skipping leading blanks (or other whitespace?). The
token is terminated by the first appearance of tokchar,
or by the end of the source string.

The caller must supply sufficient space in token to
receive any token, Otherwise tokens will be truncated.

Returns: a pointer past the terminating tokchar.

This will happily return an infinity of empty tokens if
called with src pointing to the end of a string. Tokens
will never include a copy of tokchar.

A better name would be "strtkn", except that is reserved
for the system namespace. Change to that at your risk.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
*/

const char *toksplit(const char *src, /* Source of tokens */
char tokchar, /* token delimiting char */
char *token, /* receiver of parsed token */
size_t lgh) /* length token can receive */
/* not including final '\0' */
{
if (src) {
while (' ' == *src) *src++;

while (*src && (tokchar != *src)) {
if (lgh) {
*token++ = *src;
--lgh;
}
src++;
}
if (*src && (tokchar == *src)) src++;
}
*token = '\0';
return src;
} /* toksplit */

#ifdef TESTING
#include <stdio.h>

#define ABRsize 6 /* length of acceptable token abbreviations */

int main(void)
{
char teststring[] = "This is a test, ,, abbrev, more";

const char *t, *s = teststring;
int i;
char token[ABRsize + 1];

puts(teststring );
t = s;
for (i = 0; i < 4; i++) {
t = toksplit(t, ',', token, ABRsize);
putchar(i + '1'); putchar(':');
puts(token);
}

puts("\nHow to detect 'no more tokens'");
t = s; i = 0;
while (*t) {
t = toksplit(t, ',', token, 3);
putchar(i + '1'); putchar(':');
puts(token);
i++; *>> }
puts("\nUsing blanks as token delimiters");
t = s; i = 0;
while (*t) {
t = toksplit(t, ' ', token, ABRsize);
putchar(i + '1'); putchar(':');
puts(token);
i++;
}
return 0;
} /* main */

#endif
/* ------- end file toksplit.c ----------*/


I guess I don't understand what would go in the toksplit.h file
or even why it would be nessisary: it worked fine without it.
If you could elaborate it would be much apreciated. Also thanks
really good example.


The toksplit.h file would normally contain the prototype for
toksplit, and thus be available for inclusion in another source
file that uses the routine. Gussied up with such things as
multi-inclusion protection, etc. The result is:

/* ------- file toksplit.h ----------*/
#ifndef H_toksplit_h
# define H_toksplit_h

# ifdef __cplusplus
extern "C" {
# endif

#include <stddef.h>

/* copy over the next token from an input string, after
skipping leading blanks (or other whitespace?). The
token is terminated by the first appearance of tokchar,
or by the end of the source string.

The caller must supply sufficient space in token to
receive any token, Otherwise tokens will be truncated.

Returns: a pointer past the terminating tokchar.

This will happily return an infinity of empty tokens if
called with src pointing to the end of a string. Tokens
will never include a copy of tokchar.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
*/

const char *toksplit(const char *src, /* Source of tokens */
char tokchar, /* token delimiting char */
char *token, /* receiver of parsed token */
size_t lgh); /* length token can receive */
/* not including final '\0' */

# ifdef __cplusplus
}
# endif
#endif
/* ------- end file toksplit.h ----------*/

Glad to see you have learned to properly include context from the
google excuse for an interface. Now you also need to learn that
your answer belongs after, or possibly intermixed with, the
material you quote. You should also normally snip anything out of
the quoted material that is not germane to your answer.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
May 26 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2288
by: MJackson | last post by:
I'm new to perl. I need to read in the mailbox (mbox) and break it apart into seperate emails. Of course each email may be different lengths. Each email starts with From, but there are other lines in the email starting with From: (notice the colon). So, an email starts at From and ends at the character prior to the next From. I then need to store each email off into it's own file, numbered such as 00001, 00002, etc. there will be very...
27
31405
by: The Bicycling Guitarist | last post by:
Hi. I found the following when trying to learn if there is such a thing as a non-breaking hyphen. Apparently Unicode has a ‑ but that is not well-supported, especially in older browsers. Somebody somewhere said: Alternately, you can use CSS to declare a class having: ..nowrap { white-space:nowrap } .... and then wrap the compound word in a <span class=nowrap></span> tag (or any other suitable inline tag). You can also try {...
1
1805
by: John | last post by:
Hi I need to break a memo field apart by the individual lines of text it has. I only need the last two lines. How do I do this in a query? Thanks Regards
3
1921
by: Daniel Weinand | last post by:
hello ng, i have a problem and a imho an insufficient method of solution. strings should be sorted by specific text pattern and dispayed in groups. the strings are stored in a db and have the following layout: 1.0.0.0 1.1.0.0 1.1.1.0 1.1.2.0
1
1411
by: Beenish Sahar Khan | last post by:
I have a string in following format , XXdd XXX Where X exists b/w. A - z d exists b/w. 0 - 9 I want to format them in the following manner, xxdd xxx xx dd xxx xxd dxxx
10
1845
by: Bonj | last post by:
Hello. I hope somebody can help me on this, because I'm running out of options to turn to. I have almost solved my regular expression function. Basically it works OK if unicode is defined. It doesn't work OK in ANSI mode however, as it has to use MultiByteToWideChar and WideCharToMultiByte. I've discovered that the regular expression part is working fine. As far as I can tell the regular expression code is correctly parsing what it...
150
6498
by: tony | last post by:
If you have any PHP scripts which will not work in the current releases due to breaks in backwards compatibility then take a look at http://www.tonymarston.net/php-mysql/bc-is-everything.html and see if you agree with my opinion or not. Tony Marston http://www.tonymarston.net
1
1777
by: rcamarda | last post by:
I have a column that has text delimited by a percent sign that I wish to turn into rows. Example: A column contains ROBERT%CAMARDA, I want to turn that into two rows, one row with ROBERT and antoher row with CAMARDA. I will have source rows that have zero, one, or many percent sign delimiters that will correspond to that many rows (One percent sign will create 2 rows, 2 percent signs will create 3 rows and so forth). Any thoughts?
4
2331
by: lstrudeman | last post by:
Hello; A friend gave me this syntax and they are unavailable at the moment and I need this asap. I am trying to figure out how SQL figures this out. Below the syntax takes a field in a file and breaks apart the pieces of the key for other uses. The field looks like this 1234567*AWD*07FA (or 1234567*FPER*07FA). I just need to understand how the numbers behind the TA_2007_ID field work to break apart they key?? The first one is easy.. it...
0
8189
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8692
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8635
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7182
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4089
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1499
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.