给定字符串str [],任务是检查字符串是否包含任何特殊字符,并且如果字符串具有特殊字符,则打印“不接受该字符串”,否则打印“该字符串被接受”。
特殊字符是既不是数字字符也不是字母的字符,即−!@#$%^&*()+ =-\] ['; /。,{} |::<>?`〜
因此,在C编程语言中,我们将使用if-else方法解决问题。
输入− str [] = {“教程点”}
输出-字符串不被接受
输入− str [] = {“ nhooo”}
输出-字符串被接受
遍历整个字符串。
将寻找特殊字符,如果字符串中确实存在特殊字符,则打印“字符串不被接受并中断”。否则,打印字符串被接受。
如果我们使用Java或任何其他支持正则表达式概念的语言进行编码,则将使用正则表达式来检查给定字符串中是否存在正则表达式,而不是if-else方法。这不仅是一种简单的方法,而且是一种快速的方法。
Start In function int special_character(char str[], int n) Step 1→ initialize i and flag and set flag as 0 Step 2→ Loop For i = 0 and i < n and ++i If(str[i] == '!' || str[i] == '@' || str[i] == '#' || str[i] == '$' || str[i] == '%' || str[i] == '^' || str[i] == '&' || str[i] == '*' || str[i] == '(' || str[i] == ')' || str[i] == '-' || str[i] == '{' || str[i] == '}' || str[i] == '[' || str[i] == ']' || str[i] == ':' || str[i] == ';' || str[i] == '"' || str[i] == '\'' || str[i] == '<' || str[i] == '>' || str[i] == '.' || str[i] == '/' || str[i] == '?' || str[i] == '~' || str[i] == '`' then Print "String is not allowed” Set flag as 1 break Step 3→ If flag == 0 then, Print "string is accepted” In function int main(int argc, char const *argv[]) Step 1→ Declare and set str[] as {"Tutorials-point"} Step 2→ set n as strlen(str) Step 3→ special_character(str, n) Stop
#include <stdio.h> #include <string.h> int special_character(char str[], int n){ int i, flag = 0; for (i = 0; i < n; ++i){ //checking each character of the string for special character. if(str[i] == '!' || str[i] == '@' || str[i] == '#' || str[i] == '$' || str[i] == '%' || str[i] == '^' || str[i] == '&' || str[i] == '*' || str[i] == '(' || str[i] == ')' || str[i] == '-' || str[i] == '{' || str[i] == '}' || str[i] == '[' || str[i] == ']' || str[i] == ':' || str[i] == ';' || str[i] == '"' || str[i] == '\'' || str[i] == '<' || str[i] == '>' || str[i] == '.' || str[i] == '/' || str[i] == '?' || str[i] == '~' || str[i] == '`' ){ printf("String is not allowed\n"); flag = 1; break; } } //if there is no special charcter if (flag == 0){ printf("string is accepted\n"); } return 0; } int main(int argc, char const *argv[]){ char str[] = {"Tutorials-point"}; int n = strlen(str); special_character(str, n); return 0; }
输出结果
如果运行上面的代码,它将生成以下输出-
String is not allowed