Wednesday, February 5, 2014

Search C-String for a Specific Character

First character of a c-style string which is terminated with a '\0' char can be pointed by a char pointer , " char *ptr ". In addition to that, it is possible to use a char array, " char arr[] " for storing c-style strings. char *ptr and char arr[] can be used interchangeably.

Following sample project created by qt creator and contains following files:
1- SearchCStringForSpecificChar.pro
2- main.cpp


SearchCStringForSpecificChar.pro file contains project configuration.

TEMPLATE = app
CONFIG += console
SOURCES += main.c

main.c file contains main method which is including the algorithm that is traversing the given sample c-string "asd1 a1sd1" to search for the '1' character.
#include <stdio.h>

int main(void)
{
    const char* charArray1 = "asd1 a1sd1";
    const char* charArray2 = "asd1 a1sd1";
    printf("initial char pointer charArray1 is pointing to : %s\n", charArray1);
    printf("char pointer charArray1 is pointing to the start address of the c-string: %d \n\n", charArray1);

    int strLength = 0;
    int foundCharCount = 0;

    while(*charArray1!='\0')
    {
        printf("%c - %c - %c\n", *charArray1, charArray1[0], charArray2[strLength]);
        printf("current char pointer is pointing to the address of : %d\n\n", charArray1);

        if(*charArray1=='1')
            foundCharCount++;

        strLength++;
        charArray1++;
    }

    if(*charArray1 == '\0')
        printf("Found end of string character and exited the while loop: %d\n", *charArray1);

    printf("total number of characters : %d\n", strLength);
    printf("total number of '1' characters : %d\n", foundCharCount);
    printf("last char pointer str is pointing to :%d\n\n", *charArray1);


    return 0;
}

Both charArray1 and charArray2 pointers are containig the same const char values. Till the end-of-string character, '\0' , is found the while loop iterates in the main function.

For the current item *charArray1, charArray1[0] and charArray2[strLength] all gives the same value. If the current value is '1' then the foundCharCount variable is incremented by one.

If the current value is not '\0' then increment the strLength variable by one and move the current char pointer charArray1 to the next address location in memory for checking. Console output contains all the printf function results as follows :

No comments:

Post a Comment