簡體   English   中英

C —刪除字符串中所有多余的空格(指定字符之間的字符除外)

[英]C — Remove all extra spaces in string excluding chars between specified characters

我有這個字符串: print "Foo cakes are yum"我需要以某種方式去除所有多余的空格,但在引號之間保留文本。 這是我到目前為止所擁有的:

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"

我需要能夠在引號之間跳過文本,以便得到此信息: print "Foo cakes are yum"

這是相同的問題,但對於php,我需要交流答案: 刪除字符串中的空格,不包括指定字符之間指定的空格

請幫忙。

嘗試這個:

#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為true,則跳過空格刪除。

另外,您的原始函數永遠不會為newstr分配內存。 我添加了newstr = malloc(...)部分。 在寫入字符串之前為字符串分配內存很重要。

我簡化了您的邏輯。

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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM