How to remove non-numeric characters?

Asked

Viewed 760 times

2

I want to remove all non-numeric characters from a string. I found the function isdigit that could help me. With it, I’ve gone through all the characters of a string and those that are numeric, I add in another string.

The problem with this "solution" is that at the end of the algorithm, the target variable had not only numeric characters, but also all other characters of the initial string.

My code:

#include <stdio.h>
#include <ctype.h>

void apenasNumeros(char *texto, char *dest)
{
    int i, j;
    int length = strlen(texto);

    j = 0;
    for ( i = 0; i < length; i++ ) {
        if ( isdigit(texto[i]) ) {
            dest[j++] = texto[i];
        }
    }
}

void main()
{
    char cpf[14] = "123.456.789-00";
    char cpfApenasNumeros[11];

    apenasNumeros(cpf, cpfApenasNumeros);

    printf("%s\n", cpfApenasNumeros);
    getchar();
}

The variable cpfApenasNumeres should receive the value 12345678900, but it gets 12345678900123.456.789-00.

Can anyone explain to me what I’m doing wrong and why it happens?

1 answer

2


A string must always end in \0 to be correct, which he lacked put in function apenasNumeros:

void apenasNumeros(char *texto, char *dest)
{
    int i, j;
    int length = strlen(texto);

    j = 0;
    for ( i = 0; i < length; i++ ) {
        if ( isdigit(texto[i]) ) {
            dest[j++] = texto[i];
        }
    }

    dest[j] = '\0'; //terminador aqui
}

The sizes you set for the strings are also not correct because they do not contemplate the terminators and should be:

char cpf[15] = "123.456.789-00";
char cpfApenasNumeros[15];

Example in Ideone

Note that in the cpfApenasNumeros I put the same size as the original as it could potentially only have numbers in the string you want to parse.

  • 1

    Ahh yes, it makes sense. I had forgotten that detail.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.