Home > front end >  Function to filter non digit characters in a string
Function to filter non digit characters in a string

Time:06-12

So I'm currently trying to create a function to filter out non digit characters but I can only use strlen. For example, "a4n55" -> "455" I've attempted it and I feel like I'm close. The printf's are just for testing.

void filterNonDigitCharacters(char inData[], char outData[])
{

    // create variables
    int stringLen, i, j;
    
    // get string length
    stringLen = strlen(inData);

    printf("Before filter: %s\n", inData);
    // loop across string
    for(i = 0; i < stringLen; i  )
    {
        // check if char is a number        
        if(inData[i] >= '0' && inData[i] <= '9')
        {
            outData[i] = inData[i];         
            printf("Filtering number: %c at location: %d\n", outData[i] , i);
        }
        // check if char is a letter
        else if(inData[i] >= 'a' && inData[i] <= 'z')
        {
            j = i;
            printf("Letter found : %c at index: %d\n", inData[i], i);
            outData[j] = inData[i   1];
            printf("Moving number down: %c\n", outData[j]);
        }
    }   
    outData[i] = inData[i]; 
    printf("New String: %s\n", outData);
}

CodePudding user response:

There is no need to do anything in the event a character is not a digit. Simply maintain a separate index for the output, and increment it only when a digit is found.

Remember to null-terminate the result.

void filterNonDigitCharacters(char inData[], char outData[])
{
    size_t j = 0;
    size_t length = strlen(inData);

    for (size_t i = 0; i < length; i  )
    {
        if (inData[i] >= '0' && inData[i] <= '9')
        {
            outData[j  ] = inData[i];
        }
    }

    outData[j] = 0;
}

Consider the use of <ctype.h> functions such as isdigit for determining character classes.

  • Related