parsing string on a certain character

msullivan3's Avatar, Join Date: Apr 2009
Go4Expert Member
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
0
karthigayan's Avatar, Join Date: Feb 2010
Go4Expert Member
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 like this
0
msullivan3's Avatar, Join Date: Apr 2009
Go4Expert Member
this will work for me. thanks for your reply!
0
raju00003's Avatar
Newbie Member
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;
}
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.