簡體   English   中英

如何在C中的字符串中添加逗號分隔的值

[英]How to add comma separated values in string in C

如何在字符串中添加所有csv值?

我做了一個骨架,但是我應該將字符串轉換為整數並使用+=來添加所有整數嗎?

#include <stdio.h>
int main(void)
{
    int i;                  // index
    int num=0, sum=0;       // number
    char str[]="123,456,789";

    for(i=0; str[i]; i++) {
        if (str[i] == ',') { // begin a new number
            - ① - // multiple statements are allowed
        } else { // a digit
            num = ②;
        }
    }
    sum += num; 
    printf("Sum of all values in CSV[%s] : %d", str, sum);

    return 0;
}

有很多方法可以解決此問題。 首選方法是簡單地將strtol用於其預期目的,並使用endptr參數遍歷字符串,以在成功轉換后將字符串中的位置更新為最后一位之后的位置。

但是,在學習使用數組索引 (最好是指針 )遍歷字符串以解析字符串中的內容時,具有很好的價值。 解析指針對沒有什么太復雜的了,它在字符串中寸步前進,挑出所需的東西。

在這里,您似乎想要遍歷字符串中的每個字符,測試逗號或數字,並采取適當的措施將數字添加到您的number ,或者在遇到逗號時將您的number添加到sum 別忘了,在將數字用於字符之前,必須將其ASCII值轉換為數值。

您嘗試的內容的簡單實現如下所示:

#include <stdio.h>

int main(void)
{
    int i,
        num=0,
        sum=0;
    char str[] = "123,456,789";

    for (i = 0; str[i]; i++)    /* loop over each char */
        if (str[i] == ',') {    /* begin a new number */
            sum += num;         /* add number to sum */
            num = 0;            /* reset number to 0 */
        }
        else                    /* add digit to number */
            num = num * 10 + (str[i] - '0');

    sum += num;                 /* add final number to sum */

    printf ("Sum of all values in CSV[%s] : %d\n", str, sum);

    return 0;
}

使用/輸出示例

$ ./bin/csvsum
Sum of all values in CSV[123,456,789] : 1368

一個strtol實施

之所以選擇strtol (或任何strtoX家族)的原因是由於它們提供了轉換的錯誤檢查以及將字符串內的指針內置轉換為數字后的下一個字符的內置前進方式。 。 (在您的情況下,每次轉換后, endptr參數將指向字符串中的commanul終止字符。

這使您可以簡單地使用strtol和一對指針( pep 指針結束指針 )在字符串中向下移動,並在使用strtol (p, &ep, base)將每組數字轉換為數字。 每次成功轉換后,只需向前跳ep直到找到下一個'+-''0-9'開始下一次有效的轉換並設置p = ep; 並重復。 (如果在前進ep達到零終止字符-您知道轉換已完成)

一個簡單的實現是:

#include <stdio.h>
#include <stdlib.h>     /* for strtol */
#include <limits.h>     /* for INT_MAX */
#include <errno.h>      /* for errno */

#define BASE 10         /* added benefit - strtol will convert from many bases */

int main (void)
{
    int sum=0;
    long tmp = 0;                   /* tmp long for strtol conversion */
    char str[] = "123,456,789",
        *p = str, *ep = NULL;       /* pointer and end-pointer */

    for (;;) {                      /* perform conversion until end (or error) */
        errno = 0;                      /* reset errno */
        tmp = strtol (p, &ep, BASE);    /* perform conversion, update ep */
        if (errno) {                    /* check conversion was valid */
            fprintf (stderr, "error: invalid conversion.\n");
            return 1;
        }
        if (tmp < INT_MAX - sum)        /* make sure tmp will fit in sum */
            sum += (int)tmp;            /* add tmp to sum */
        else {
            fprintf (stderr, "error: sum overflowed.\n");
            return 1;
        }
        /* find the next '+-' or 'digit' or end of string */
        while (*ep && *ep != '+' && *ep != '-' && ( *ep < '0' || '9' < *ep))
            ep++;
        if (!*ep) break;    /* if *ep is nul-character, end reached, bail */
        p = ep;             /* update pointer to end-pointer, repeat */
    }

    printf ("Sum of all values in CSV[%s] : %d\n", str, sum);

    return 0;
}

仔細檢查一下,如果您還有其他問題,請告訴我。

首先,您可以修剪所有空白和所有空白。

其次,正如您所提到的,只有整數之間用逗號分隔,因此您應該了解獲取整數的一般方法。

那是什么主意?

除非看到逗號或字符串結尾,否則將繼續形成數字。

號碼如何形成?

|ABCD
      num
A|BCD  A   [Here also 10*0+A]
AB|CD  A*10+B
ABC|D  (A*10+B)*10+C
ABCD|  ((A*10+B)*10+C)*10+D = 1000*A+100*B+10*C+1*D

您將現有數字重復乘以10,然后將其相加。

這樣您就可以形成號碼。

我避免給出函數的答案。 還有其他選項,例如使用諸如strtok等內置函數。您可以參考進行檢查。

您可以使用strtokstrtol函數執行所需的操作:

int main(void)
{
    /* delimiter: string will be cut on spaces and comma */
    char delim[] = " ,";
    char *tok;
    /* string to parse */
    char str[] = "123,465,798";

    int sum = 0, num;

    /* get first token, warning `str` is modified */
    tok = strtok(str, delim);
    while (tok)
    {
        /* convert token to int */
        num = strtol(tok, NULL, 0);

        /* add it to sum */
        sum += num;

        /* read next token */
        tok = strtok(NULL, delim);
    }
    printf("sum is %d\n", sum);
    return 0;
}
int main() {

    int i;  // index

    int iGroup=0;// groupNumber array

    int num=0, sum=0;       // number
    char str[]="123,456,789";
    char strNum[16];
    memset(&strNum[0], 0, sizeof(strNum));

    for(i=0; str[i]!='\0'; i++) {
        if (str[i] == ',' ) { // Get the group number array since the numbers 

            iGroup=0;                     //Reset the index of the groupNumber array
            num=atoi(strNum);                 //Convert the array to numbers
             memset(&strNum[0], 0, sizeof(strNum)); //Set the groupNumber array to null 
                   sum += num; 
        } else { // a digit
            strNum[iGroup]=str[i];             //Add the character to groupNumber array
            iGroup++;
        }
    }
       num=atoi(strNum); 
       sum += num;
    //sum += num; 
    printf("Sum of all values in CSV[%s] : %d", str, sum);

    return 0;
}

這是使用strtol()strspn()的解決方案,它不會修改輸入字符串:

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

int sum_csv(const char *str) {
    int sum = 0;
    for (;;) {
        char *p;
        int n = strtol(str, &p, 10);  /* convert number */
        if (p == str)                 /* stop if no number left */
            break;
        sum += n;                     /* accumulate (ignore overflow) */
        str = p + strspn(p, ", ");    /* skip number and delimiters */
    }
    return sum;
}

int main(void) {
    printf("sum is %d\n", sum_csv("123,465,798");
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM