简体   繁体   English

在 C 中计算空格 -argc/argv

[英]Counting whitespaces -argc/argv in C

I would like to count whitespaces, like ' ' (ASCII SP or 32).我想计算空格,如' ' (ASCII SP 或 32)。 I have to pass the arguments using the command line.我必须使用命令行传递参数。 So for example, I enter Hello World and would like to receive the amount of whitespaces, in this case the result should be 2.例如,我输入 Hello World 并希望接收空格的数量,在这种情况下,结果应该是 2。

I already tried following: Text = Hello World我已经尝试过: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);
         }
     }
}

I know that *(argv + 1) is Hello ( or ASCII number) and *(argv + 2) = World and thats the problem I do have.我知道*(argv + 1)Hello (或 ASCII 数字)和*(argv + 2) = World这就是我遇到的问题。 How can I count the spaces between the argv[n] ?如何计算argv[n]之间的空格? The amount of whitespaces can be different, so therefore I don't want to code like If(argc > 1){ spaces++;} .空格的数量可能会有所不同,因此我不想像If(argc > 1){ spaces++;}那样编码。

Can someone help?有人可以帮忙吗?

Best regards,此致,

Keita凯塔

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

If you execute:如果执行:

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

the shell is going to extract the arguments to the command by splitting the input command into arguments at the positions of a sequence os spaces (a contiguous sequence of spaces, tabs and/or newlines), and comments (like the above one) are eliminated from imput, so if you issue the command above, you'll get an argv like this: shell 将通过将输入命令拆分为序列 os 空格(空格、制表符和/或换行符的连续序列)位置处的参数来提取命令的参数,并消除注释(如上述)从输入,所以如果你发出上面的命令,你会得到一个这样的argv

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

in case you use quotes to delimit arguments, you can issue如果您使用引号来分隔参数,则可以发出

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

and it that case you will get something like:在这种情况下,你会得到类似的东西:

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

In that case you'll get the spaces into the arguments.在这种情况下,您会将空格放入参数中。

Important重要的

You don't check the number of arguments passed to a.out so in the case you post, you can be trying to pass NULL pointer to strlen() which will result in Undefined Behaviour.您不检查传递给a.out的参数数量,因此在您发布的情况下,您可以尝试将NULL指针传递给strlen()这将导致未定义行为。 This is an error, for your program to work correctly you might do the following (i have corrected some other errors and commented them in comments in your code):这是一个错误,为了让您的程序正常工作,您可能会执行以下操作(我已更正了一些其他错误并在您的代码的注释中对其进行了注释):

#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 */
}

and this code could be simplified (taking advantage of mystring being a pointer, by moving the pointer until we reach the end of string (pointing to a \\0 char) with this approach (it also avoids to compute the string length, which makes another pass on the string ---unnecessary)并且可以简化此代码(利用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);
}

and finally, you have a <ctype.h> header with functions like isspace(c) to check if a character is a space (in this case, it checks for space and tab characters.最后,您有一个<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