如何在C中检查字符串的特定格式

时间:2017-08-20 21:15:08

标签: c

我有以下代码接受类似小时的字符串..我想检查字符串格式是否实际为xx-yy其中xxyy类似于一小时。代码工作正常但是当我输入"02-13-"时它返回true但我希望它返回false因为它不正确(因为它最后有-

bool hourIsValid(char * hours) {
  int openH = 0;
  int closeH = 0;

  if ((sscanf(hours, "%d-%d", & openH, & closeH) == 2) && openH >= 0 && openH <= 24 && closeH >= 0 && closeH <= 24) {
    if (openH >= closeH) {
      return false;
    }
    return true;
  } else {
    return false;
  }
}

2 个答案:

答案 0 :(得分:1)

解决方案取决于&#34; pedantic&#34;在确定输入是否有效时,您的代码必须是。例如,您可能希望"2-14""02 - 15"" 2-14 "有效,或者您可能不会。这取决于。

如果你想获得一个只接受确切格式"dd-dd"而没有前导或尾随字符或空格并且每小时值只有两位数格式的迂腐版本,你可以检查字符串为在使用sscanf - 代码:

读取值之前
if (strlen(hours) != 5)
    return 0;

if (hours[2] != '-')
    return 0;

if ( !isdigit(hours[0])
    || !isdigit(hours[1])
    || !isdigit(hours[3])
    || !isdigit(hours[4])
    )
    return 0;

答案 1 :(得分:0)

另一种方式:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

bool hourIsValid(
      char *I__hours
      )
   {
   long openH, closeH;

   openH=strtol(I__hours, &I__hours, 10);
   if(      '-' != *I__hours                   // Ensure that there is a dash between the two numbers in the string.
         || 0 >= openH                         // Ensure that the 1st number in the string is non-negative.
         || 24 <= openH                        // Ensure that the 1st number in the string is 24 or less.
         )
      return(false);

   ++I__hours;                                 // Skip over the dash between the two numbers.
   closeH=strtol(I__hours, &I__hours, 10);
   if(      *I__hours                          // Ensure that there are no additional characters beyond the 2nd number.
         || 0 >= closeH                        // Ensure that the 2nd number in the string is non-negative.
         || 24 <= closeH                       // Ensure that the 2nd number in the string is 24 or less.
         || openH >= closeH                    // Ensure that the 1st number is less or equal to the 2nd number.
         )
      return(false);

   return(true);
   }