C -> Finding all occurences of a character in a string

C -> Finding all occurences of a character in a string

Advertisemen

The algorithm may not be the most effecient - O(n^2) - but I whipped it up quickly and it works. I also wanted to play around with the memset function which I haven't used before


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

//returns an array with the index values
int *parseString(char *str,char parseFor)
{
       int i;
       int count=0;
       int *retVal;
       int inputLength = strlen(str);
       //boolean array
       unsigned char *storeIndex = (unsigned char*) malloc (inputLength);
       memset(storeIndex,0,inputLength); //defualt values

       //parse string
       for (i=0;i<inputLength;i++)
              if (str[i]==parseFor)
              {
                     storeIndex[i]=1;
                     count++;
              }

       retVal = (int*) malloc (count*sizeof(int));
       count = 0;

       for (i=0;i<inputLength;i++)
              if (storeIndex[i])
                     retVal[count++] = i;
lass="MsoNormal" style="line-height: normal; margin-bottom: .0001pt; margin-bottom: 0cm; mso-layout-grid-align: none; text-autospace: none;">       return retVal;

}

int main(void)
{
       char buffer[256];
       int *parsedIndexes;
       char parseFor[2];
       int i;
       int size;
       int linePosition=0;

      
       fprintf(stdout,"Enter your string: ");
       gets(buffer);
      
       fprintf(stdout,"Enter the character to search for: ");
       gets(parseFor); parseFor[1] = '\0';

       parsedIndexes = parseString(buffer,parseFor[0]);

       fprintf(stdout,"\n%s\n",buffer);

       size = sizeof(parsedIndexes);
       for (i=0;i<size;i++)
       {
              while (linePosition++ != parsedIndexes[i] && linePosition != strlen(buffer)) fprintf(stdout," ");
              if (linePosition != strlen(buffer)) fprintf(stdout,"^");
       }
       fprintf(stdout,"\n");

       return 0;
}

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Game Engine Tutorial