C语言检查数组字符串中是否有space?

A check in C language if there is a space inside the array string?

如何检查数组字符串中是否有space? 你可以帮帮我吗?提前致谢 ;)

for ( i = 0;  string[i] != '[=11=]';  ++i )
        if ( string[i]) != ' ' )

error: expected expression

您可以使用标准函数 strchr(string, ' ') - return 一个 non-NULL 指针,如果 string 内部有 space:

if(strchr(string, ' '))
{
    // printf( "string contain space" );
}

参考strchr函数:

7.24.5.2 The strchr function

     #include <string.h>
     char *strchr(const char *s, int c);

3 The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.

您在 if 条件

中提供了额外的 )
if ( string[i]) != ' ' )
//here--------^

删除它或用 (

平衡它
if (string[i] != ' ' )
//OR
if ((string[i]) != ' ' )

始终确保检查程序中 () 的数量是否相等 ;)

既然你想检查数组中是否存在 space,你可以这样做:

for ( i = 0;  string[i] != '[=12=]';  ++i )
    if (string[i] != ' ' )
       break;

if(string[i] != '[=12=]')
    printf("space found at index no: %d", i); 

如果您想知道数组中存在的 space 的总数,请使用变量作为计数器并在找到 ' ' 时递增它:

int count = 0;

for ( i = 0;  string[i] != '[=13=]';  ++i )
    if (string[i] != ' ' )
       count++

正如我在评论中所说,您的问题标题和您提供的代码存在问题。两者是不同的东西。

如果您删除位于此处的额外 ),您的代码就可以了:

if ( string[i]) != ' ' )

试试这个代码:

#include <stdio.h>

int main(void){
    const char *string = "This is a String";
    int i = 0;
    int count = 0;

    for ( i = 0;  string[i] != '[=11=]';  ++i ){
        if ( string[i] != ' ' ){
            count++;
        }
    }

    printf("Number of Letters found are: %d\nNumber Of spaces Found are %d\n", count, (i - count));
}

输出:

Number of Letters found are: 13
Number Of spaces Found are 3

这取决于你"space"的意思。

标准头文件 <ctype.h> 指定了一个函数 isspace(),该函数测试其参数是否对应于当前语言环境中的 whitespace。有多个字符 isspace() 可以 return 为真(例如,在大多数说英语的人会使用的 C 语言环境中,return 对 space 字符为真,换行符、水平和垂直制表符、回车 return 和换页)。

如果您只想将单个字符视为 space,请使用 strchr()。如果要指定一组全部被视为白色的字符space,请使用strpbrk()。这两个函数都在 <string.h>.

中声明

如果您不想使用这些函数,那么对于您决定用于确定单个字符是否为 space 的任何测试,只需循环遍历字符串的所有元素,并测试每个元素.使用 "standard strings"(就像字符串文字,例如 "Hello there" 这意味着迭代直到找到值为零的字符 ('[=17=]')。

顺便说一句:您提到的编译器错误的原因是第二行的额外 )