2016-01-23 728 views
0

我有這個字符串:print "Foo cakes are yum" 我需要以某種方式去除所有多餘的空格,但在引號之間留下文本。這是我到目前爲止有:C ---刪除字符串中的所有多餘空格,排除指定字符之間的字符

char* clean_strip(char* string) 
{ 
    int d = 0, c = 0; 
    char* newstr; 
    while(string[c] != '\0'){ 
     if(string[c] == ' '){ 
      int temp = c + 1; 
      if(string[temp] != '\0'){ 
       while(string[temp] == ' ' && string[temp] != '\0'){ 
        if(string[temp] == ' '){ 
         c++; 
        } 
        temp++; 
       } 
      } 
     } 
     newstr[d] = string[c]; 
     c++; 
     d++; 
    } 
    return newstr; 
} 

這將返回字符串:print "Foo cakes are yum"

我需要能夠跳過文本之間THW行情,所以我得到這樣的:print "Foo cakes are yum"

這裏是同樣的問題,但對於PHP,我需要一個C答案:Remove spaces in string, excluding these in specified between specified characters

請幫助。

+0

使用'strtok'。它會刪除您指定的分隔符。 –

回答

1

試試這個:

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

char* clean_strip(char* string) 
{ 
    int d = 0, c = 0; 
    char* newstr = malloc(strlen(string)+1); 
    int quoted = 0; 

    while(string[c] != '\0'){ 
     if (string[c] == '"') quoted = !quoted; 

     if(!quoted && string[c] == ' '){ 
      int temp = c + 1; 
      if(string[temp] != '\0'){ 
       while(string[temp] == ' ' && string[temp] != '\0'){ 
        if(string[temp] == ' '){ 
         c++; 
        } 
        temp++; 
       } 
      } 
     } 

     newstr[d] = string[c]; 
     c++; 
     d++; 
    } 
    newstr[d] = 0; 
    return newstr; 
} 


int main(int argc, char *argv[]) 
{ 
    char *input = "print  \"Foo cakes  are yum\""; 
    char *output = clean_strip(input); 
    printf(output); 
    free(output); 
    return 0; 
} 

這將產生輸出:

print "Foo cakes  are yum" 

它通過尋找"字符。如果發現它切換變量quoted。如果quoted爲真,則刪除空白字符。

另外,您的原始函數從未爲newstr分配內存。我添加了newstr = malloc(...)部分。在寫入字符串之前爲字符串分配內存非常重要。

+0

我收到了一大堆指向malloc函數的錯誤。它只是一個C++函數嗎? – ThatPixelCherry

+4

'malloc'是一個C函數。將'#include '放在文件的最頂端。 – 2016-01-23 04:03:44

+0

確保你還有'string.h'和'stdio.h'。 – 2016-01-23 04:05:11

0

我簡化了你的邏輯。

int main(void) 
{ 
    char string[] = "print  \"Foo cakes  are yum\""; 
    int i = 0, j = 1, quoted=0; 
    if (string[0] == '"') 
    { 
     quoted=1; 
    } 
    for(i=1; i< strlen(string); i++) 
    { 
     if (string[i] == '"') 
     { 
      quoted = 1-quoted; 
     } 
     string[j] = string[i]; 
     if (string[j-1]==' ' && string[j] ==' ' && !quoted) 
     { 
      ; 
     } 
     else 
     { 
      j++; 
     } 
    } 
    string[j]='\0'; 
    printf("%s\n",string); 
    return 0; 

} 
相關問題