繁体   English   中英

在 C 中计算空格 -argc/argv

[英]Counting whitespaces -argc/argv in C

我想计算空格,如' ' (ASCII SP 或 32)。 我必须使用命令行传递参数。 例如,我输入 Hello World 并希望接收空格的数量,在这种情况下,结果应该是 2。

我已经尝试过:Text = Hello World

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]){
    int spaces = 0;
    char* mystring = argv[1];
    int size = strlen(argv[1]) + strlen(argv[2]);
     for(int i = 0; i < size; i++){
         if((*(mystring + i)) == ' '){
             spaces++;
             printf("%d\n", spaces);
         }
     }
}

我知道*(argv + 1)Hello (或 ASCII 数字)和*(argv + 2) = World这就是我遇到的问题。 如何计算argv[n]之间的空格? 空格的数量可能会有所不同,因此我不想像If(argc > 1){ spaces++;}那样编码。

有人可以帮忙吗?

此致,

凯塔

在双引号中传递字符串,例如“Hello World”。

如果执行:

$ a.out Hello      world # There are 5 spaces between both args here.

shell 将通过将输入命令拆分为序列 os 空格(空格、制表符和/或换行符的连续序列)位置处的参数来提取命令的参数,并消除注释(如上述)从输入,所以如果你发出上面的命令,你会得到一个这样的argv

int argc = 3;
char *argv[] = { "a.out", "Hello", "world", NULL, };

如果您使用引号来分隔参数,则可以发出

$ a.out "Hello     world"  # there are also 5 spaces between the words.

在这种情况下,你会得到类似的东西:

int argc = 2;
char *argv[] = { "a.out", "Hello     world", NULL, };

在这种情况下,您会将空格放入参数中。

重要的

您不检查传递给a.out的参数数量,因此在您发布的情况下,您可以尝试将NULL指针传递给strlen()这将导致未定义行为。 这是一个错误,为了让您的程序正常工作,您可能会执行以下操作(我已更正了一些其他错误并在您的代码的注释中对其进行了注释):

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
    int spaces = 0;
    int arg_ix;  /* index of the argument to consider */
    for (arg_ix = 1; arg_ix < argc; arg_ix++) { /* so we don't check more arguments than available */
        char *mystring = argv[arg_ix];
        int size = strlen(mystring);
        for(int i = 0; i < size; i++) {
            if(mystring[i] == ' '){  /* why use such hell notation? */
                spaces++;
            }
        }
    }
    printf("%d\n", spaces); /* print the value collected at the end, not before */
}

并且可以简化此代码(利用mystring作为指针,通过使用这种方法移动指针直到我们到达字符串的末尾(指向\\0字符)(它还避免计算字符串长度,这使得另一个传递字符串 --- 不必要)

#include <stdio.h>
/* string.h is not needed anymore, as we don't use strlen() */

int main(int argc, char* argv[]){
    int spaces = 0;
    int arg_ix;
    for (arg_ix = 1; arg_ix < argc; arg_ix++) {
        char* mystring = argv[arg_ix];
        for( /* empty */; *mystring != '\0'; mystring++) {
            if(*mystring == ' '){
                spaces++;
            }
        }
     }
     printf("%d\n", spaces);
}

最后,您有一个<ctype.h>标头,其中包含诸如isspace(c)类的函数来检查字符是否为空格(在这种情况下,它检查空格和制表符。

#include <stdio.h>
#include <ctype.h>

int main(int argc, char* argv[]){
    int spaces = 0;
    int arg_ix;
    for (arg_ix = 1; arg_ix < argc; arg_ix++) {
        char* mystring = argv[arg_ix];
        for(; *mystring != '\0'; mystring++) {
            if(isspace(*mystring)){
                spaces++;
            }
        }
     }
     printf("%d\n", spaces);
}

暂无
暂无

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

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