用C代替两个字符

时间:2018-01-14 21:47:38

标签: c replace character strchr

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

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;
}

这很好用,但实际上我想替换我的"?" by"?\ n"。 strcat不能用指针工作就是这样吗?我可以找到一个解决方案,在我的字符串中添加一个字符并将其替换为' \ n',但这不是我真正想要的。

谢谢!

1 个答案:

答案 0 :(得分:0)

修改

在你的初步回答中,你提到过你想追加换行符 ?,但现在这个参考已经消失了。

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

新答案

您必须更改strqclean功能

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

OLD ANSWER

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;
}