Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   parsing string on a certain character (http://www.go4expert.com/forums/parsing-string-character-t21591/)

msullivan3 30Mar2010 23:13

parsing string on a certain character
 
Hi,

i am reading in a date string as hh:mm:ss and trying to store the values in hh, mm, and ss. the input would read as something like 21:43:33. I have looked at some functions like strtok and strchr but not really sure which is most effective. Would appreciate it if someone has an easy answer to this

Thanks

karthigayan 31Mar2010 09:55

Re: parsing string on a certain character
 
strtok is the best way for this,

Code:

#include <stdio.h>
#include <string.h>
int main ()
{
  char str[] ="15:30:12";
  char *hh,*mm,*ss;
  hh = strtok (str,":");
  mm = strtok (NULL,":");
  ss = strtok (NULL,":");
  printf("%s,%s,%s",hh,mm,ss);
  return 0;
}


msullivan3 31Mar2010 10:17

Re: parsing string on a certain character
 
this will work for me. thanks for your reply!

raju00003 31Mar2010 10:41

Re: parsing string on a certain character
 
here is the Code for what you need ..try this

Code:


#include <string>

#include <iostream>

using namespace std;

int splitString( string input,string seperatior);

int main()
{


    std::string input = "21:30:33";

    splitString (input,":");

    return 0;
}

int splitString (string input,string seperator)
{

    size_t i = input.find(seperator);

    if ( i!=string::npos )
    {
   
        size_t y = 0;

        string hour = "";

        if (!input.empty())
        {
            while ( y!=i)
            {
                hour += input[y++];
            }           
        }

        cout << hour << endl;

    }
   
    return 0;
}

;)

xpi0t0s 31Mar2010 12:01

Re: parsing string on a certain character
 
Rather than calling lots of functions, if the input format is guaranteed you can do something like:
Code:

char *tm="21:43:33";
int hh=tm[0]*10+tm[1]-'0'*11;
int mm=tm[3]*10+tm[4]-'0'*11;
int ss=tm[6]*10+tm[7]-'0'*11;

especially if after splitting the strings into smaller strings you're then converting them to numbers.


All times are GMT +5.5. The time now is 21:03.