[英]How to check for special characters in a 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')){
你可能想要這樣的東西:
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')){
...
}
但最好的方法是使用標准函數並將if((ch >= 'a'
替換為:
if (!isalpha(ch)) {
...
更好的是:將字符串中是否有特殊字符的檢查外包給 function:
將整個for (j =
loop 替換為:
if (ContainsSpecialChars(record[i].EmpName)) {
...
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
}
不要忘記#include <ctypes.h>
用於isalpha
function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.