gpt4 book ai didi

c - 如何连接两个字符串,其中源字符串应附加在目标字符串之前?

转载 作者:太空宇宙 更新时间:2023-11-04 05:21:50 25 4
gpt4 key购买 nike

我遇到了另一个 C 问题。如何连接两个字符串,第二个字符串插入到第一个字符串之前?

这是我想出来的。不幸的是,我被所有这些指向字符、字符数组等的指针困住了。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[] )
{
char* output;
int i;
for(i = 9; i > 0; i--)
{
unsigned int value = (unsigned int)i;
char buffer[20];
sprintf(buffer, "%u", value);
// strcat(ouput, buffer); // append before the string.
// first loop: 9
// second loop: 89
// third loop: 789
}

printf("%s", output);
}

我必须如何更正我的代码才能使其正常工作?我想我必须以某种方式将输出变量设置为空。什么时候需要 char 数组或指针的固定宽度? 20 只是我的随机猜测。

最佳答案

我很困惑,因为您发布的代码与您陈述的问题完全无关。 (好吧,他们都使用字符串,但仅此而已)

  char* src  = "Hello, ";
char* dest = "World!";

char* temp;
temp = malloc(strlen(src) +strlen(dest) + 1);
strcpy(temp, src);
strcat(temp, dest);

dest = temp;

除非 dest 是一个大小足以容纳组合字符串的固定缓冲区。如果是,则将最后一行替换为:

  strcpy(dest, temp);
free(temp);

现在,如果您想专门反向构建数字列表,让我们尝试不同的方法:

  char buffer[10];
buffer[9] = '\0'; // null terminate our string.
char* output;
int i;
for(i = 9; i > 0; i--)
{
// this is a fast way of saying, sprintf("%u", i);
// works only for single digits
char d = (char)('0' + i);

buffer[i-1] = d;
output = &buffer[i-1];
printf("%s", output);
}

关于c - 如何连接两个字符串,其中源字符串应附加在目标字符串之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3586015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com