Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我怎样才能使C能把字母和单词分开呢_C_Function - Fatal编程技术网

我怎样才能使C能把字母和单词分开呢

我怎样才能使C能把字母和单词分开呢,c,function,C,Function,首先,如果我的问题不被理解的话,我为这个模糊的标题感到抱歉。英语是我的第三语言,很难清楚地表达这个问题。这是我的问题,我想引入一个化学物质公式,比如H3PO4,程序应该把H分开,给他一个变量名,比如x(我们有3x,因为它是H3),PO4是另一个变量,比如y。或者使用更简单的物质,如HCl,程序应将其在H和Cl中分离。您可以通过测试大写字母、小写字母和数字来分解化学式: #include <ctype.h> #include <stdio.h> #include <s

首先,如果我的问题不被理解的话,我为这个模糊的标题感到抱歉。英语是我的第三语言,很难清楚地表达这个问题。这是我的问题,我想引入一个化学物质公式,比如H3PO4,程序应该把H分开,给他一个变量名,比如x(我们有3x,因为它是H3),PO4是另一个变量,比如y。或者使用更简单的物质,如HCl,程序应将其在H和Cl中分离。

您可以通过测试大写字母、小写字母和数字来分解化学式:

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

struct element {
    char symbol[3];
    int n;
};

// decompose a formula into an array of elements and counts
int decompose(char *s, struct element *a, int length) {
    int i = 0;
    while (*s) {
        if (isupper((unsigned char)*s) && i < length) {
            int j = 0;
            a->symbol[j++] = *s++;
            if (islower((unsigned char)*s)) {
                a->symbol[j++] = *s++;
            }
            a->symbol[j] = '\0';
            a->n = 1;
            if (isdigit((unsigned char)*s)) {
                a->n = strtol(s, &s, 10);
            }
            i++;
            a++;
        } else {
            return -1;  // syntax error
        }
    }
    return i;  // number of elements
}

int main(int argc, char *argv[]) {
    struct element array[10];
    for (int i = 1; i < argc; i++) {
        int n = decompose(argv[i], array, sizeof(array) / sizeof(*array));
        if (n < 0) {
            printf("%s: syntax error\n", argv[i]);
        } else {
            printf("%s:\n", argv[i]);
            for (int j = 0; j < n; j++) {
                printf("    %d %s\n", array[j].n, array[j].symbol);
            }
        }
    }
    return 0;
}

我假设您的输入是大写的:

#包括
#包括
#包括
内部主(空){
int-var[26];
memset(var,0,sizeof(var));
char*s=“H3PO4”;
对于(int i=0;i对于(int i=0;i它需要相当复杂,因为你要分离
HCl
的元素,而不是
PO
的元素。你尝试过什么?化学中的原子符号有一个非常好的特性,它们都以一个大写字母开头,后面可能是小写字母。因此每个大写字母是一个新符号。然而,您似乎对PO4(-3)等离子感兴趣,而不是只对原子感兴趣?为此,您需要一些预先制作的常见离子列表。或者要求您的输入使用一些括号,例如H3(PO4),当您对整个离子进行重复计数时,无论如何都需要这些括号。这就是我们所称的完整程序!;)我认为误读了他需要的东西,我的程序只存储不同的原子,但它可以改进
s[I]&&isdigit(s[I])
是多余的:
isdigit(0)
无论如何都是假的。只要写
isdigit((无符号字符)s[I])
还要注意的是,并非所有化学元素符号都有一个字母,例如:
Cl
表示氯,
Na
表示氮……但它们都以大写字母开头,可以选择后跟小写字母,如图所示。超重元素的符号有两个小写字母,直到它们都被正式命名为in 2016。元素具有此类符号,但不太可能出现在任何化学式中。
gcc chemistry.c && ./a.out 
Atom H: 3
Atom O: 4
Atom P: 1