使用c验证模式 [英] Validating a pattern using c
本文介绍了使用c验证模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用c验证字符串模式
模式123-456-789,即位置3& 7应该是破折号,其他应该是数字值
i我在下面验证如下
< pre lang =C ++> for ( int iny = 0 ; iny< ilength; iny ++)
{
if (isdigit((pszSeqCodeObjName [iny]) &&((iny!= 3 || iny!= 7 ))
{
validation = true ;
}
else
{
if (pszSeqCodeObjName [ 3 ] == ' - ' || pszSeqCodeObjName [ 7 ] == ' - ')
{
validation = true ;
}
其他
{
validation = false ;
}
建议是否可以做更好的逻辑
快速响应高度赞赏!!。
解决方案
我会简化它:
bool valid = true ;
for ( int i = 0 ; i< iLength&&有效; i ++)
{
if (i == 3 || i == 7 )
{
valid = pszSeqCodeObjName [i] == ' - ';
}
else
{
valid = isdigit(pszSeqCodeObjName [i]);
}
}
static bool match( const char * text, const char * pattern)
{
while (* text&& * pattern)
{
switch (* pattern)
{
case ' # ':
if (!isdigit(* text))
return false ;
默认:
如果(* pattern!= * text)
return false ;
}
text ++;
pattern ++;
}
返回 * text == 0 && * pattern == 0 ;
}
int main( int , char **)
{
const char text [] = 123-45-6789;
const char pattern [] = ### - ## - ####;
printf( %s应用于%s返回%d。\ n, pattern,text,match(text,pattern));
return 0 ;
}
i want to validate a string pattern using c
pattern 123-456-789 i.e position 3 & 7 should be dash and others should be numeric value
i am validating it as below as below
for( int iny = 0; iny < ilength ; iny++ )
{
if(isdigit((pszSeqCodeObjName[iny]) && ((iny != 3 || iny != 7))
{
validation= true;
}
else
{
if(pszSeqCodeObjName[3] == '-'|| pszSeqCodeObjName[7] =='-')
{
validation= true;
}
else
{
validation= false;
}
suggest if any better logic can be done
quick response highly Appreciated !!.
解决方案
I would simplify it a little:
bool valid = true; for (int i = 0; i < iLength && valid; i++) { if (i == 3 || i == 7) { valid = pszSeqCodeObjName[i] == '-'; } else { valid = isdigit(pszSeqCodeObjName[i]); } }
static bool match(const char *text, const char *pattern) { while (*text && *pattern) { switch (*pattern) { case '#': if ( !isdigit(*text) ) return false; default: if (*pattern != *text) return false; } text++; pattern++; } return *text == 0 && *pattern == 0; } int main(int, char **) { const char text[] = "123-45-6789"; const char pattern[] = "###-##-####"; printf("%s applied to %s returns %d.\n", pattern, text, match(text, pattern)); return 0; }
这篇关于使用c验证模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文