在c中添加字符串的ascii值的最佳方法?

时间:2012-12-20 16:53:53

标签: c

我想添加一个字符串的ascii值,比如“hello”。 在c中这样做的最佳方法是什么?有没有循环字符串的方法?

2 个答案:

答案 0 :(得分:3)

当然,你可以不用循环来做到这一点:

#include <stdio.h>

int sum(const char *s) { return *s == 0 ? 0 : *s + sum(s + 1); }

int main()
{
    printf("%d\n", sum("hello"));
    return 0;
}

答案 1 :(得分:1)

没有循环就没办法做到这一点,除非你在编译时知道字符串的长度。

char *str = "hello";
int total = 0;

while(*str) { total += *str++; }