Francisco Cruz Francisco Cruz -4 years ago 103
C Question

Extract numbers from a character string in C

Please can you tell me what is wrong in the program I've written?
I'm trying to create a new string with the numbers found in a string entered by the user.


For example: "Enter a string: helloeveryone58985hohoh kgkfgk878788

answer: 58985878788

if numbers are not found, then the answer should be: "No changes in string."


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

#define MK 20
#define ML 81

void changeStr(char str[],char New[]){
int i,j=0,n;

for(i=0;i<)
}

int main(){
char str[ML],New[ML]={0};
printf("Enter string: \n");
gets(str);
changeStr(str,New);
printf("Changed string:\n");
printf("%s",New);
if(New[0] == '\0'){
printf("No changes in string.\n");
}
return 0;
}

Answer Source

this should work :

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

#define ML 81

char    *changeStr(char *str)
{
    char *new = NULL;;
    int i = 0;
    int length = 0;

    /* calulating the size to allocate with malloc for new */
    while (str[i])
    {
        if (str[i] >= 48 && str[i] <= 57)
            length++;
        i++;
    }

    /* if no numbers found, return new which is NULL */
    if (length == 0)
        return new;
    new = malloc(length * sizeof(char));
    i = 0;
    length = 0;

    /* filling new with numbers */
    while (str[i])
    {
        if (str[i] >= 48 && str[i] <= 57)
        {
            new[length] = str[i];
            length++;
        }
        i++;
    }
    new[length] = 0;
    return new;
}

/* I kept the functions you are using in the main, i would not
   use gets, but it's maybe easier for you to keep it */

int main()
{
    char str[ML]={0};
    char *New;

    printf("Enter string: \n");
    gets(str);
    New = changeStr(str);
    if(!New){
        printf("No changes in string.\n");
    }
    else
    {
        printf("Changed string:\n");
        printf("%s",New);
    }
    return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download