1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

/**
 * Input: string pos (passed as a_pos)
 * Output: ch - first character in the string
 * Output: num_occurances - number of times that character occured
 * Returns: true if at the end of the string
 */
bool count_consecutive_characters(int* a_num_occurances, char* a_ch,
        char const** a_pos) {
    *a_num_occurances = 0;
    *a_ch = **a_pos;
    while (**a_pos == *a_ch) {
        // this works: (*a_pos)++;
        // this does not: *a_pos++;
        // *a_pos++ is same as *(a_pos++)
        *a_pos += 1;
        *a_num_occurances += 1;
    }
    return **a_pos == '\0';
}

void test_string_abc() {
    char ch;
    int num_occurances;
    char const* input = "aaabbcccc";
    char const* pos = input;
    bool at_string_end = count_consecutive_characters(
            &num_occurances, &ch, &pos);
    assert(!at_string_end);
    printf("ch '%c', num_occurances %d, at_string_end %d\n",
            ch, num_occurances, at_string_end);
    assert(ch == 'a');
    assert(num_occurances == 3);
    assert(pos == input + 3);
    
    at_string_end = count_consecutive_characters(
            &num_occurances, &ch, &pos);
    assert(!at_string_end);
    printf("ch '%c', num_occurances %d, at_string_end %d\n",
            ch, num_occurances, at_string_end);
    assert(ch == 'b');
    assert(num_occurances == 2);
    assert(pos == input + 3 + 2);

    at_string_end = count_consecutive_characters(
            &num_occurances, &ch, &pos);
    assert(at_string_end);
    printf("ch '%c', num_occurances %d, at_string_end %d\n",
            ch, num_occurances, at_string_end);
    assert(ch == 'c');
    assert(num_occurances == 4);
    assert(pos == input + 3 + 2 + 4);
}

int main(int argc, char* argv[]) {
    test_string_abc();
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.