lpy
lpy

Reputation: 587

How to compare the string in C++?

checkFormat(string &s)
{

}

string s is a string that indicate the date.

I want to compare a string s, to find whether it is in terms of "yyyy:mm::dd" or not.

What should I do?

compare it char by char? What if the string is "600:12:01" ?

Sorry for my poor English.

Upvotes: 2

Views: 314

Answers (6)

unwind
unwind

Reputation: 399703

Here's one idea for an algorithm:

  1. Check that the length is the expected one. This is quick.
  2. Check that the colons are in the expected places.
  3. Check that the first four characters are digits.
  4. Check that the middle two characters are digits.
  5. Check that the final two characters are digits.

If either test fails, return false. If you get through them all, return true.

Of course, this doesn't validate the ranges of the values. Also, you're not really "comparing", you are "validating".

Upvotes: 2

MSalters
MSalters

Reputation: 179779

Don't use regex. Use strptime(), which is designed to parse time strings (hence the name: str p time, string -> parse -> time). A regex can't figure out that 2013:2:29 is invalid.

Upvotes: 4

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

Does your compiler support regular expressions, i.e. are you using a somewhat C++11 compliant compiler? This would make the task much easier … Otherwise you might want to resort to Boost.Regex.

Assuming that you can use C++11, the following code should do what you want (untested though):

std::regex rx("\\d{4}:\\d{2}:\\d{2}");
return regex_match(s.begin(), s.end(), rx);

John Cook has written an introduction into C++ regular expressions. Just replace every occurrence of std::tr1 by std if your compiler supports C++11.

Upvotes: 0

teukkam
teukkam

Reputation: 4317

This is the job for regular expressions. Since you're using C++, Boost.Regex is one option.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258548

You can use Boost Regex to check whether the string matches your pattern.

Upvotes: 1

graham.reeds
graham.reeds

Reputation: 16476

Easiest would to be slice the string into its component parts of year, month, day and compare those.

See here to split strings by delimiter.

Upvotes: 0

Related Questions