c - 如何用一个字符替换多字符字符常量

标签 c string

我正在尝试替换 '%7C''|'在 C 中,但我收到多字符字符常量警告。我想知道是否可以做到这一点,如果可以的话怎么做?我尝试使用下面的代码,但它给出了此警告。

解析.c

char *parse(char *command){
 char * newCommand = (char *)malloc(sizeof(char)*35);
     newCommand = strtok(command, " ");
     newCommand = strtok(NULL, "/run?command= ");
     for(int i = 0; i<strlen(newCommand); i++){
          if(newCommand[i] == '+')
          {
              newCommand[i] = ' ';
          }
          if(newCommand[i] == '%7C')
          {
               newCommand[i] = '|';
          }
     }
    return newCommand;
  }

最佳答案

多字符常量不可移植,通常应避免。您的代码属于“常规”类别。

解决问题的部分方法是进行字符串比较(使用 strncmp):

if (strncmp(&newCommand[i], "%7C", 3) == 0)
{
    newCommand[i] = '|';
}

但是,您还需要删除7C。这需要在循环上进行更多手术:

int tgt = 0;
int len = strlen(newCommand);
for (int src = 0; src < len; src++)
{
    if (newCommand[src] == '+')
    {
        newCommand[tgt++] = ' ';
    }
    else if (strncmp(newCommand[i], "%7C", 3) == 0)
    {
        newCommand[tgt++] = '|';
        src += 2;
    }
    else
        newCommand[tgt++] = newCommand[src];
 }
 newCommand[tgt] = '\0';

这会在 newCommand 数组中维护两个索引,一个是您从中读取的索引 (src),另一个是您正在写入的索引 (tgtdst 是一个替代名称)。将 % 替换为 | 后,src += 2; 会跳过 7C

未编译的代码!

另外,在你的函数中你有:

char *newCommand = (char *)malloc(sizeof(char)*35);
newCommand = strtok(command, " ");

这会立即泄漏分配的内存。也许您需要使用 strdup() 或:

char *newCommand = malloc(strlen(command) + 1);
if (newCommand == NULL) …report error and bail out…
strcpy(newCommand, command);

下一行:

newCommand = strtok(NULL, "/run?command= ");

分割常量字符串中任意字符的任意序列;它不会查找该字符串。如果您想查找字符串,那么您需要 strstr() ,并且您可能需要首先运行 strtok() 以获得正确的起点(也许 newCommand = strtok(NULL, ""),然后 char *end = strstr(newCommand, "/run?command= "); — 并检查返回的空指针.

通过修改后的分配,您需要一个新符号来记录 strtok() 返回的指针 - 例如 char *token;

总而言之,您的代码需要做很多工作。

关于c - 如何用一个字符替换多字符字符常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045259/

相关文章:

c - GCC __attribute__ ((对齐 (8))) 不起作用

c - 为什么 NULL 与 '\0' 不同

c - Haskell 到 C - 自定义数据类型

mysql - 按字符串中的数字对现有数据库进行排序

java - 我如何反转这个基本加密?

php - PHP 使用什么子字符串算法(查找字符串)?

c - 将字符串分配给动态 int 数组时的重新分配问题

python - 从python列表中过滤对象

python - python中切片的这种行为是什么?

python - 查找并提取字符串中的多个子字符串?