使用c在给定的字符串文本中添加三位数字

时间:2015-06-26 19:38:39

标签: c string puzzle

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

int add(char s[])
{
    char p[3];
    int i=0, j=0, sum=0;
    for(i=0;s[i]!='\0';i++) 
    {
        if(isdigit(s[i])&&isdigit(s[i+1])&&isdigit(s[i+2])&&!isdigit(s[i+3])&&!isdigit(s[i-1]))
        {
            p[0]=s[i];
            p[1]=s[i+1];
            p[2]=s[i+2];
            sum+=atoi(p);
        }

    }
    return sum;
}

上面我尝试编写代码,在字符串文本中只添加三位数字,但它不起作用。无法弄清问题是什么。

4 个答案:

答案 0 :(得分:1)

如果我理解你想要在字符串中添加前三位数的总和,那么你肯定会以艰难的方式去做。将字符串传递给函数后,只需指定一个指向字符串的指针并检查字符串中的每个字符。如果char是数字,则将数字添加到sum。找到3位数字后,只需返回总和即可。 (您也可以使您的函数一般返回您选择的任意位数的总和)。

注意:在将数字的ascii值添加到sum之前,必须将其转换为数字值。 (即ascii char 9 - '0'是数字9等等。)(见ascii character values

这是一个简短的例子,它使用上面的方法添加字符串中的前3位数字。如果您有任何疑问或需求,请告诉我。

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

int add_ndigits (const char *s, size_t ndigits)
{
    const char *p = s;      /* pointer to string */
    int sum = 0;
    size_t count = 0;

    while (*p) {                        /* for each char in string  */
        if (*p >= '0' && *p <= '9') {   /* check if it is a digit   */
            sum += *p - '0';            /* if so add value to sum   */
            count++;                    /* increment digit count    */

            if (count == ndigits)       /* if count = ndigits break */
            break;
        }
        p++;
    }

    return sum;   /* return the sum of the first ndigits in string  */
}

int main (void) {

    char string[] = "this is 1 string with 2 or 3 more digits like 1, 2, 7, etc.";

    int sum3 = add_ndigits (string, 3);

    printf ("\n The sum of the first 3 digits in 'string' is: %d\n\n", sum3);

    return 0;
}

<强>输出

$ ./bin/add3string

 The sum of the first 3 digits in 'string' is: 6

答案 1 :(得分:1)

简单的替代

int add(char s[]) {
    int c = 0, ans = 0;
    for (const char * d = s; *d; ++d)
        if (isdigit(*d) && c < 3) {
            ans += (*d - '0');
            ++c;
        }
    return ans;
}

答案 2 :(得分:0)

char p[3]无法容纳3个字符。您需要为null终止符添加额外的字节。 您可以将其声明为char char p[4]并执行memset以避免与null终止混淆如下:

`memset(p,'\0',sizeof(p));`

如果您有任何疑虑,请告诉我。

答案 3 :(得分:0)

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

int add(char s[])
{
    char *p;
    unsigned sum=0;
    do {
        while(!isdigit(*s) && *s)   /* Skip nondigits except \0 */
            ++s;
        p=s;
        if(isdigit(*s) && isdigit(*++s) && isdigit(*++s))
            if(isdigit(*++s))   /* more than 3 digits? */
                while(isdigit(*++s))    /* then skip rest of digits */
                    {}
            else {
                if(*p == '0') { /* prevent atoi from reading octal */
                    if(*++p == '0')
                        ++p;
                }
                sum += atoi(p);
            }
    } while(*s);
    return sum;
}
编辑:我太傻了。

我从未喜欢过
        if(isdigit(p[0]=s[i]) && isdigit(p[1]=s[++i]) && isdigit(p[2]=s[++i]))

开头。