1

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

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”的解决方案,但这不是我真正想要的。

谢谢 !

4

1 回答 1

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允许您连接字符串。\n如果?字符始终位于字符串的末尾,您可以使用 than 来附加。如果要替换的字符在中间,则必须在中间插入字符。为此,您可以使用 usememmove来在目标和源重叠时移动内存块。

#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;
}
于 2018-01-14T22:19:56.307 回答