2017-05-20 9 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

오류 : '(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 –

관련 문제