簡體   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