Creator: Andrew Mascolo (HazardsMind)
Modified: 8/20/2016 Date: 10/23/2015

struct Data // must have
{
  char string[20];
  int counter;
};

struct Data CountStrings(char * str, int * found, struct Data myData[])
{
  static int count = 0;
  static int N = 1;

  boolean unique = false; // no match

  for ( int j = 0; j < N; j++ )
  {
    if ( strcmp( myData[j].string, str ) == 0 ) // compare entered string with what is in the buffer
    {
      ++myData[j].counter;
      unique = true; //match found
      break;
    }
  }
  if (!unique) // if no match, then add it
  {
    strcpy(myData[N - 1].string, str);
    ++myData[N-1].counter; // this ensures that counter will at least show 1 occurrence of that string
    *found = N;
    N++;
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  struct Data Result[20]={"\0"}; // MUST be null string
  int found = 0;
  char *strings[] = {"apple", "banana", "cantaloupe", "apple", "kiwi", "apple", "banana"};

  for (int i = 0; i < 7; i++)
    CountStrings(strings[i], &found, Result);

  CountStrings("kiwi", &found, Result); // add another string

  for(int r = 0; r < found; r++)
  {
     Serial.print(F("Found: ")); Serial.print(Result[r].string); Serial.print(F("\t")); Serial.println(Result[r].counter);
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

Result:

apple 3
banana 2
cantaloupe 1
kiwi 2


Raw C++ code

// http://cpp.sh/5atv6
#include <iostream>
#include <cstring>

struct Data
{
  char string[20];
  int counter;
};

void CountStrings(char * str, int * found, struct Data myData[])
{
  static int N = 1;

  int unique = 0; // no match

  for ( int j = 0; j < N; j++ )
  {
    if ( strcmp( myData[j].string, str ) == 0 )
    {
      ++myData[j].counter;
      unique = 1; //match found
      break;
    }
  }
  if (!unique) // if no match, then add it
  {
    strcpy(myData[N - 1].string, str);
    ++myData[N-1].counter;
    *found = N;
    N++;
  }
}

int main()
{
    int Found = 0;

    struct Data FoundData[10]={"\0"};
    char * name[] = {"Andrew", "Joseph", "Maria", "John", "Andrew", "Joseph", "Maria", "Maria", "Joseph", "Andrew"};

    for(int i = 0; i < 10; i++)
      CountStrings(name[i], &Found, &*FoundData);

    CountStrings("John", &Found, &*FoundData); // append name individually
    for(int i = 0; i < Found; i++)
      std::cout<< FoundData[i].string << "\t" << FoundData[i].counter <<"\n";      
}

Share