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

Selective removal of specific char in a string

假设我有一个看起来像这样的字符串:

  "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 != '[=13=]') 
{
    if (*src != c)   
    {
        *dest = *src;  
        dest++;        
    }
    src++;         
}
*dest = '[=13=]';        
}

它删除了 str 中所有出现的 char c 并且我虽然我应该使用更多的条件表达式来仅在以下情况下进行删除某些事情发生了。

有线索吗?

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

要跟踪该信息,您可以使用一个附加变量,每次出现 ".

时都会更新该变量
int quoted = 0;

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

   // delete only if !quoted
   ...
}

我只是想这样做。下面是我的程序。

注意: 这可能不是一个有效的程序(时间不佳或 space 复杂),但是它可以完成您想要做的事情(如果我理解您的问对了)。

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

#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 != '[=10=]')
    {
            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 = '[=10=]';
    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);
}

您还需要一个变量来用作某种标志,表示之后“您需要删除 spaces。然后您将以某种方式在 if() 语句中使用该标志.这里int removeFlag是我用过的flag.