选择性删除字符串中的特定字符

时间:2015-02-19 02:13:49

标签: c arrays string text char

假设我有一个字符串可能如下所示:

  "value" "some other value"   "other value"  "some value"     

我的目标是有选择地删除空白,如下所示:

"value""some other value""other value""some value"

这样空格仅>在引号中包含的字符串中

"some other value"  

我有以下功能:

void rmChar(char *str, char c)
{
char *src, *dest;
src = dest = str; 

while(*src != '\0') 
{
    if (*src != c)   
    {
        *dest = *src;  
        dest++;        
    }
    src++;         
}
*dest = '\0';        
}

删除 str 中出现的所有char c ,我虽然应该使用更多的条件表达式来仅在某些事情发生时才进行删除。

有任何线索吗?

2 个答案:

答案 0 :(得分:1)

迭代字符串的循环必须跟踪它是否正在查看带引号的字符串中的字符,然后使用该信息仅在适当时删除。

要跟踪这些信息,您可以使用每次有"时都会更新的其他变量。

int quoted = 0;

while (...) {
   if (*src == '"') {
     // set `quoted` to 1 or 0, as appropriate
     ...
   }

   // delete only if !quoted
   ...
}

答案 1 :(得分:1)

我只想到这样做。以下是我的计划。

注意:这可能不是一个有效的程序(糟糕的时间或空间复杂性),但它会做你想做的事情(如果我理解你的问题)。

注意此外,我在此代码中使用了malloc()。如果您在不使用任何其他字符串的情况下更改原始字符串的内容,则不会使用它。但正如我从你的问题中所理解的那样,你创建了一个新的字符串,其中包含删除空格后原始字符串的值。

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

void rmChar(char *,char, int );
int main()
{
    char string[200] = "\"This is a value\"  \"and another value\"   \"value2 this\"";
    char c;
    c = '"';
    printf("%s\n",string);
    int len = strlen(string);
    /*Pass the address of the stringi, char c, and the length of the string*/
    /*Length of the string will be required for malloc() inside function rmChar()*/
    rmChar(string, c, len);

    return 0;
}

void rmChar(char *str,char c, int len)
{
    char *dest1, *dest2;
    char *src = str;

    int removeFlag = 0; /* You will remove all the spaces ' ' that come after removeFlag is odd*/

    dest1 = malloc(len);
    dest2 = dest1;

    while(*str != '\0')
    {
            if(*str == c)
            {
                    removeFlag++;
                    if (removeFlag %2 == 0)
                    {
                            /* This is required because every 2nd time you get a " removeFlag is increased so next if is NOT true*/
                            *dest2 = *str;
                            dest2++;
                    }
            }
            if ((removeFlag % 2) == 1)
            {
                    *dest2 = *str;
                    dest2++;
            }
            str++;
    }
    *dest2 = '\0';
    printf("%s\n", dest1);
    /* If you want to copy the string without spaces to the original string uncomment below line*/

    //strcpy(src, dest1);

    free(dest1);
}

你还需要一个变量来作为某种标志使用,之后表示&#34;你需要删除空格。然后,您将以某种方式在if()语句中使用该标志。这里int removeFlag是我用过的旗帜。