How can I make that C can apart letters from an word

Viewed 72

First of all sorry for the hazy title and if my question isn't understood .English is my third language and is kinda hard to formulate the question clearly . Here's my problem I want to introduce a chemical substance formula like H3PO4 and the the program should separate H and to give him a variable name like x(and we will have 3x because its H3) and PO4 to be another variable like y. Or a simpler substance like HCl and the program should separate it in H and Cl .

2 Answers

You can decompose the chemical formula by testing for capital letters, lower case letters and digits:

#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;
}

Sample run:

$ ./chem HCl H3PO4 XePtF6
1 H
1 Cl
H3PO4:
3 H
1 P
4 O
XePtF6:
1 Xe
1 Pt
6 F

I assume you will have the input in uppercases:

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

int main(void) {
    int var[26];
    memset(var, 0, sizeof(var));
    char *s = "H3PO4";
    for (int i = 0; i < strlen(s); ) {
        char c = s[i++];
        int n = 1;
        if (isdigit((unsigned char)s[i])) {
            n = 0;
            while (isdigit((unsigned char)s[i]))
                n = n * 10 + s[i++] - '0';
        }
        var[c - 'A'] += n;
    }

    for (int i = 0; i <26; i++)
        if (var[i])
            printf("Atom %c: %d\n", i  + 'A', var[i]);
}

Output:

gcc chemistry.c && ./a.out 
Atom H: 3
Atom O: 4
Atom P: 1
Related