简体   繁体   English

如何检查字符串中的特殊字符?

[英]How to check for special characters in a string?

How can I check whether there is a special character in my string when my input stored in a pointer?当我的输入存储在指针中时,如何检查字符串中是否有特殊字符? I tried this code but it seems that it will only check for the first char and not the whole string.我尝试了这段代码,但似乎它只会检查第一个字符而不是整个字符串。

void EmployeeDetails(int count, account_s record[count]){  /* Function to get employee details */
    
    int i;
    char ch;
    EmployeeName: 
    for(i = 0; i < count; i++){ // count here is the amount of employee from main function      
        
        printf("\nEnter employee name: "); 
        scanf("%s", record[i].EmpName);
        ch = record[i].EmpName[i];
     
        if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){

You probably want something like this:你可能想要这样的东西:

void EmployeeDetails(int count, account_s record[count]){  /* Function to get employee details */
    
    int i;
    EmployeeName: 
    for(i = 0; i < count; i++){ // count here is the amount of employee from main function      
        
        printf("\nEnter employee name: "); 
        scanf("%s", record[i].EmpName);

        for (j = 0; j < strlen(record[i].EmpName); j++)
        {
          char ch = record[i].EmpName[j];
          if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
            ...
        }

But the best way is to use on of the standard functions and replace if((ch >= 'a' with this:但最好的方法是使用标准函数并将if((ch >= 'a'替换为:

if (!isalpha(ch)) {
   ...

Even better: outsource the checking if there are special characters in the string to a function:更好的是:将字符串中是否有特殊字符的检查外包给 function:

Replace the whole for (j = loop with:将整个for (j = loop 替换为:

   if (ContainsSpecialChars(record[i].EmpName)) {
      ...

with ContainsSpecialChars being: ContainsSpecialChars为:

int ContainsSpecialChars(const char name[])
{
   // Returns 1 if name contains a special character. Otherwise returns 0.
   //
   // I let you write this as an exercise
}

Don't forget #include <ctypes.h> for the isalpha function.不要忘记#include <ctypes.h>用于isalpha function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM