n4t*_*i0s 4 c arrays function c-strings char
我编写了这个简单的代码来检查字符串是否仅包含字母和空格
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int checkString(char str1[]);
void main()
{
char str1[N];
scanf("%s", str1);
printf("%d",checkString(str1));
getch();
}
int checkString(char str1[])
{
int i, x=0, p;
p=strlen(str1);
for (i = 0; i < p ; i++)
{
if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] == ' '))
{
continue;
}
else{ return 0; }
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
当我输入类似以下内容时,效果很好:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int checkString(char str1[]);
void main()
{
char str1[N];
scanf("%s", str1);
printf("%d",checkString(str1));
getch();
}
int checkString(char str1[])
{
int i, x=0, p;
p=strlen(str1);
for (i = 0; i < p ; i++)
{
if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] == ' '))
{
continue;
}
else{ return 0; }
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
但如果我在空格后输入任何内容,它就会返回1,如下所示:
hello asds //returns 1
hello1010 sasd // return 0
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我为什么吗?
isalpha如果使用标准C函数并isblank在头文件中声明,则函数可以写得更简单和正确<ctype.h>例如
#include <ctype.h>
//...
int checkString( const char s[] )
{
unsigned char c;
while ( ( c = *s ) && ( isalpha( c ) || isblank( c ) ) ) ++s;
return *s == '\0';
}
Run Code Online (Sandbox Code Playgroud)
如果您想检查字符串是否包含空格,那么isblank您应该使用 function 而不是 function isspace。
请考虑到在如此简单的循环中使用语句并不是一个好主意continue。最好重写循环而不使用该continue语句。
scanf如果您想输入一个句子,最好使用函数而不是函数。fgets该函数允许将多个单词作为一个字符串输入,直到按下 Enter 键为止。
例如
fgets( str1, sizeof( str1 ), stdin );
Run Code Online (Sandbox Code Playgroud)
考虑到该函数包含换行符。因此,输入字符串后,您应该删除该字符。例如
size_t n = strlen( str1 );
if ( n != 0 && str1[n-1] == '\n' ) str1[n-1] = '\0';
Run Code Online (Sandbox Code Playgroud)