2017-05-20 23 views
-1

請您告訴我我編寫的程序中出了什麼問題? 我正在嘗試用用戶輸入的字符串中找到的數字創建一個新的字符串。從C中的字符串中提取數字

例如:「輸入一個字符串:helloeveryone58985hohoh kgkfgk878788

答案:58985878788

如果未找到號碼,那麼答案應該是: 「字符串沒有變化」

#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; 
} 
+4

錯誤,請問這是什麼:'for(i = 0; i <)'? – alk

+0

您的程序沒有縮進。 –

+0

字符串在最後有一個0,所以你的循環可以運行,直到它擊中。你想要的功能是'isdigit' – stark

回答

1

這應該工作:

#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; 
} 
+0

謝謝你!)@ MIG-23 –

0

是,你想要什麼?

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

#define MK 20 
#define ML 81 

void changeStr(char str[],char New[]) 
{ 
    int i,iNew = 0; 
    int lenStr = strlen(str); 
    for(i=0;i<lenStr;i++) 
     if (str[i]>= '0' && str[i]<= '9') 
      New[iNew++]=str[i]; 
    New[iNew]=NULL; 
} 

int main() 
{ 
    char str[ML],New[ML]= {0}; 
    printf("Enter string: \n"); 
    gets(str); 
    changeStr(str,New); 

    if(New[0] == '\0') 
    { 
     printf("No changes in string.\n"); 
    } 
    else 
    { 
     printf("Changed string:\n"); 
     printf("%s",New); 
    } 
    return 0; 
} 
+0

非常感謝! @ sudipto.bd –