2012-10-26 5 views
5

질문하면 here은 내가 문제가있는 것과 매우 유사합니다. 차이점은 공백을 제거하고 결과 문자열/char 배열을 반환하는 함수에 인수를 전달해야한다는 것입니다. 공백을 없애기 위해 코드를 만들었지 만 원래 배열에서 남겨진 문자가 남아있는 이유가 있습니다. 나는 strncpy도 시도했지만 많은 오류가있었습니다.C에서 문자열/문자 배열에서 공백을 제거하는 함수

#include <stdio.h> 
#include <string.h> 
#define STRINGMAX 1000              /*Maximium input size is 1000 characters*/ 

char* deblank(char* input)             /* deblank accepts a char[] argument and returns a char[] */ 
{ 
    char *output=input; 
    for (int i = 0, j = 0; i<strlen(input); i++,j++)      /* Evaluate each character in the input */ 
    { 
     if (input[i]!=' ')             /* If the character is not a space */ 
      output[j]=input[i];            /* Copy that character to the output char[] */ 
     else 
      j--;               /* If it is a space then do not increment the output index (j), the next non-space will be entered at the current index */ 
    } 
    return output;               /* Return output char[]. Should have no spaces*/ 
} 
int main(void) { 
    char input[STRINGMAX]; 
    char terminate[] = "END\n";            /* Sentinal value to exit program */ 

    printf("STRING DE-BLANKER\n"); 
    printf("Please enter a string up to 1000 characters.\n> "); 
    fgets(input, STRINGMAX, stdin);           /* Read up to 1000 characters from stdin */ 

    while (strcmp(input, terminate) != 0)         /* Check for que to exit! */ 
    { 
     input[strlen(input) - 1] = '\0'; 
     printf("You typed: \"%s\"\n",input);        /* Prints the original input */ 
     printf("Your new string is: %s\n", deblank(input));     /* Prints the output from deblank(input) should have no spaces... DE-BLANKED!!! */ 

     printf("Please enter a string up to 1000 characters.\n> "); 
     fgets(input, STRINGMAX, stdin);          /* Read up to another 1000 characters from stdin... will continue until 'END' is entered*/ 
    } 
} 
+0

가능한 복제 [C 언어의 주어진 문자열에서 모든 공백과 탭을 제거하는 방법?] (http://stackoverflow.com/questions/1514660/how-to-remove-all-spaces-and -tabs-from-a-given-string-in-c-language) –

답변

11

당신이 NUL 종료 자 (\0) 새로운 길이가 원래 문자열보다 작거나 같은 때문에 그것을 종료되지 않은 input에서 공백을 제거한 후. 다른 사람이 언급 한 바와 같이, 같은 문자열이 소스 및 대상, 문자열의 끝 모두에 사용되는

char* deblank(char* input)           
{ 
    int i,j; 
    char *output=input; 
    for (i = 0, j = 0; i<strlen(input); i++,j++)   
    { 
     if (input[i]!=' ')       
      output[j]=input[i];      
     else 
      j--;          
    } 
    output[j]=0; 
    return output; 
} 
+0

나를 위해 잘 근무했습니다! 감사.j 선언을 for 루프 밖으로 이동시켜 함수 범위 가시성을 부여해야했습니다. –

10

당신은 출력을 종료하지 않는, 그리고이 줄어들 수도 있기 때문에, 당신이 거기에 기존의 꼬리를 떠난다 : 여기

는 내가 지금까지 가지고있는 것입니다.

또한 루프에서 항상 증가되고 현재 문자가 복사되지 않으면 수동으로 감소해야하는 j의 치료가 다소 차선책이라고 제안 할 것입니다. 매우 명확하지 않으며 원하지 않을 때 취소해야하는 무의미한 작업 (j 증가)을 수행합니다. 꽤 혼란 스럽다.

이 작성 쉽다 같은 :

char * deblank(char *str) 
{ 
    char *out = str, *put = str; 

    for(; *str != '\0'; ++str) 
    { 
    if(*str != ' ') 
     *put++ = *str; 
    } 
    *put = '\0'; 

    return out; 
} 
+0

당신의 답을 선호했을 지 모르지만 나는 유아의 포인터에 대한 이해 만 가지고 있습니다. 제가 수업을 위해 읽고있는 책은 나 자신과 같은 절대 초보자들에게 너무 잘 설명하지 못하고 솔직히 내 강사에게 무슨 일이 일어나는지 설명 할 수 없었습니다. 코드를 오랫동안 보았을 때 한 일을 함께 할 수는 있지만 실제로 코드가 어떻게 작동하는지에 대한 기본적인 개념은 없습니다. 예를 들어, "++"가 char 배열과 함께 어떻게 작동합니까? 숫자 데이터 유형에만 사용할 수 있다고 생각했습니다. 어쨌든 귀하의 의견을 주셔서 감사합니다! –

0

이 유지되지 않습니다

은 그냥 루프 끝의 그것을 NUL - 종료합니다.

다음과 같은 방법으로 수행 할 수도 있습니다.

char* deblank(char* input)             /* deblank accepts a char[] argument and returns a char[] */ 
{ 
    char *output; 
    output = malloc(strlen(input)+1); 

    int i=0, j=0; 
    for (i = 0, j = 0; i<strlen(input); i++,j++)      /* Evaluate each character in the input */ 
    { 
     if (input[i]!=' ')             /* If the character is not a space */ 
      output[j]=input[i];            /* Copy that character to the output char[] */ 
     else 
      j--;               /* If it is a space then do not increment the output index (j), the next non-space will be entered at the current index */ 
    } 

    output[j] ='\0'; 
    return output;               /* Return output char[]. Should have no spaces*/ 
} 
0

당신은 당신이 한 번에 두 개 이상의 문자를 필터링해야하는 경우 루프 블록에 대한이

char* deblank(char* input)             
{ 
char *output=input; 
for (int i = 0, j = 0; i<strlen(input); i++,j++)       
{ 
    if (input[i]!=' ')             
     output[j]=input[i];            
    else`enter code here` 
     j--;                
} 
output[j]='\0'; 
return output;               
} 
0

, 당신이 찾을 수있는 후 (\ 0) 종결 널을 추가 한 후 문자열을 반환해야 예 :

char *FilterChars(char *String,char *Filter){ 
    int a=0,i=0; 
    char *Filtered=(char *)malloc(strlen(String)*sizeof(char)); 
    for(a=0;String[a];a++) 
    if(!strchr(Filter,String[a])) 
     Filtered[i++]=String[a]; 
    Filtered[i]=0; 
    return Filtered; 
} 

유용한 정보; * 스트립하려는 필터의 문자 목록을 제공하십시오. 탭, 줄 바꿈 및 공백의 경우 "\ t \ n"과 같이 입력하십시오.

0

이 코드는 O (n)의 시간 복잡성과 함께 작동합니다.

char str[]={"my name is Om"}; 
int c=0,j=0; 
while(str[c]!='\0'){ 
    if(str[c]!=' '){ 
     str[j++]=str[c]; 
    } 
    c++; 
} 
str[j]='\0'; 
printf("%s",str); 
관련 문제