Operating System - Linux
1753637 Members
5763 Online
108798 Solutions
New Discussion юеВ

How to split strings from seperators

 
SOLVED
Go to solution
Henry Chua
Super Advisor

How to split strings from seperators

Hi Guys

Is there any way to convert "07/22/2005,19:22:54" to
07222005192254 i.e. get rid of all the seperator in between such as "/", "," and ":"..
I tried using sscanf but it doesnt seems to work.

and sadly I can only use C programming...

Best regards
Henry
5 REPLIES 5
john korterman
Honored Contributor

Re: How to split strings from seperators

Hi,
a simple way is to delete them, e.g.:
# echo "07/22/2005,19:22:54"| tr -d "\/|,|:"

regards,
John K.
it would be nice if you always got a second chance
Andrew Merritt_2
Honored Contributor
Solution

Re: How to split strings from seperators

Do you mean 'is there a single library call that will do the operation in one go'? Not sure there is.

There's several trivial ways you could do this using simple C code, e.g. just reading the string a byte at a time and not copying those characters that appear in a second string.

You could also do something similar using 'strtok()', with the second string being the set of delimiters, and just build up the target string from the returned substrings.

Andrew
Rick Garland
Honored Contributor

Re: How to split strings from seperators

If what you are interested in is having the appropriate date conversion;

date +%m%d%Y%H%M%S

will get that same output...




Tom Schroll
Frequent Advisor

Re: How to split strings from seperators


Henry,

Here is a "C" solution that I threw together in a few minutes. No warranty implied or expressed. :-)

(Attached is a Notepad text file version preserving indentations). Good luck.


#include
#include
#include
#include

#define MAXTOK 255
#define MAXBUF 1024

int main()
{
int i = 0;
char *string = "07/22/2005,19:22:54";
char *delims = "/,:";
char *tokens[MAXTOK];
char *buffer;
char **x;

/* Allocate a static buffer */
/* NOTE: there are all kinds of do's and don'ts about using malloc. */
/* Please research the correct/safe method for your site. */
if( (buffer = malloc(MAXBUF)) == NULL )
{
fprintf( stderr, "ERROR: malloc() failed.\n" );
exit( 1 );
}

/* Initialize the buffer to all NULLs */
memset( buffer, '\0', MAXBUF );

/* Use strtok to break strings up by delimiters */
tokens[0] = strtok(string, delims);
while (tokens[++i] = strtok(NULL, delims));

/* Pointer arithmetic ahead; not for the faint of heart */
x = tokens;
while( *x != NULL )
{
/* printf( "%s\n", *x ); */
strcat( buffer, *x );
x++;
}

printf( "%s\n", buffer );
}


-- Tom
If it ain't broke, it needs optimized.
Henry Chua
Super Advisor

Re: How to split strings from seperators

Thanks guys for your help.. i have implemented my solution using Strtok();