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?
It’s working for me, look this link
– danieltakeshi