2015-08-27 26 views
0

我想遍历数组arithchar中的字符以确定是否有任何输入的字符与它匹配。确定输入中是否包含算术运算符c

我的代码如下所示:

int checkForAO(char password_entered[]); 
int main(){ 
    if(checkForAO(password_entered)){ 
     //contains a password with ao 
    } 
    else{ 
     //doesnt contain special ao. 
    } 

    int checkForAO(char password_entered[]){ 
     int i; 
     char arithchar[4] = {'+','-','*','/'}; 
     for (i=0; i<strlen(password_entered); i++) { 
      if (<<<< password_entered[i] contains any character in arithchar array >>>>>>>)) { 
       printf("\nYour password contain(s) ao.\n"); 
       return true; 
      } 
     } 
     printf("\nYour password didn't contain any ao.\n"); 
     return false; 
    } 

我需要特别帮助的决定我最后的if{}声明,我试图pseudocoding了我所需要的,但似乎无法推测这一个。

谢谢。

+0

尝试'for'语句而不是'if if语句 – wimh

回答

4

使用strpbrk<string.h>

E.g

int checkForAO(char password_entered[]){ 
    if(strpbrk(password_entered, "+-*/")){ 
     printf("\nYour password contain(s) ao.\n"); 
     return true; 
    } else { 
     printf("\nYour password didn't contain any ao.\n"); 
     return false; 
    } 
} 
1

我会建议你做的是添加以下行,如果:

if (password_entered[i] == '+' || password_entered[i] == '-' || password_entered[i] == '*' || password_entered[i] == '/')) 

并删除以下行:

// char arithchar[4] = {'+','-','*','/'}; 

你的功能将变得像:

int checkForAO(char password_entered[]){ 
    int i; 

    // char arithchar[4] = {'+','-','*','/'}; 
    for (i=0; i<strlen(password_entered); i++) { 
     if (password_entered[i] == '+' || password_entered[i] == '-' || password_entered[i] == '*' || password_entered[i] == '/')) 
     { 
      printf("\nYour password contain(s) ao.\n"); 
      return true; 
     } 
    } 
    printf("\nYour password didn't contain any ao.\n"); 
    return false; 
0
 for (i=0; i<strlen(password_entered); i++) 
{ 
        for(int j=0;j<strlen(arithchar);j++) 
    { 
       if(password_entered[i]==arithchar[j]) 
       { 
         printf("\nYour password contain(s) ao.\n"); 
         return true; 
       } 
    } 
} 

会工作。

0

紧凑的解决方案,使用strchr()

int checkForAO(char password_entered[]) 
{ 
    for (i=0; i<strlen(password_entered); i++) 
    { 
     if (strchr("+-*/", password_entered[i]) != NULL) 
     { 
      printf("\nYour password contain(s) ao.\n"); 
      return true; 
     } 
    } 
    printf("\nYour password didn't contain any ao.\n"); 
    return false; 
} 

注意的是,使用strchr()使得它能够很容易地扩展。