【问题标题】:Replacing one character with two in C [duplicate]在C中用两个替换一个字符[重复]
【发布时间】:2018-06-23 13:59:48
【问题描述】:

我想用我的字符串中的两个字符替换一个字符。

void strqclean(const char *buffer)
{
  char *p = strchr(buffer,'?');
  if (p != NULL)
    *p = '\n';
}

int main(){
    char **quest;
    quest = malloc(10 * (sizeof(char*)));
    quest[0] = strdup("Hello ?");
    strqclean(quest[0]);
    printf(quest[0]);
    return;
}

这很好用,但实际上我想替换我的“?”通过“?\n”。 strcat 不适用于指针,对吗?我可以找到在我的字符串中添加一个字符并将其替换为“\n”的解决方案,但这不是我真正想要的。

谢谢!

【问题讨论】:

  • 你不能 1) 修改 const 字符串和 2) 添加比字符串可以包含的更多的数据。
  • 请发布Minimal, Complete, and Verifiable example,它显示了您尝试过的内容。发布的代码不会编译(即使放在包装器中)。 *p = strchr(buffer,'?') ==> char *p = strchr(buffer,'?')
  • 你的代码不应该工作,buffer指向const字符串,你可以改变指针但不能改变它后面的内容。
  • @Pablo 不一定,因为它是一个参数。但还是
  • @Jean-FrançoisFabre 是的,谢谢,我在按下 ENTER 后才意识到。

标签: c replace character strchr


【解决方案1】:

编辑

在您最初的回答中,您提到您想在之后添加换行符 ?,但现在这个引用已经消失了。

我的第一个答案解决了这个问题,但既然它已经消失了,我不确定你是什么 真的很想要。


新答案

你必须改变你的strqclean函数

// remove the const from the parameter
void strqclean(char *buffer)
{
  char *p = strchr(buffer,'?');
  if (p != NULL)
    *p = '\n';
}

老答案

strcat 使用指针,但 strcat 需要 C 字符串并期望 目标缓冲区有足够的内存。

strcat 允许您合并字符串。您可以使用 than 附加 \n if ? 字符始终位于字符串的末尾。如果那个字符 您要替换的是在中间,您必须在其中插入字符 中间。为此,您可以使用 memmove 来移动块 当目标和源重叠时用于内存。

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

int main(void)
{
    char line[1024] = "Is this the real life?Is this just fantasy";
    char *pos = strchr(line, '?');
    if(pos)
    {
        puts(pos);
        int len = strlen(pos);
        memmove(pos + 2, pos + 1, len);
        pos[1] = '\n';
    }
    puts(line);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    相关资源
    最近更新 更多