gpt4 book ai didi

C - 用 getpid() 中的 ID 替换字符串中的 $$?

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:46 24 4
gpt4 key购买 nike

如果我有如下字符串:

char* exampleString = "test$$";

假设 getpid() 返回 1587

如何用 getpid() 的结果替换字符串中的 $$,使结果成为字符串 "test1587"?

最佳答案

由于 "test$$" 是不可变的,指向它的指针最好是 char const* 而不是 char*必须将它复制到一个数组中,然后您可以在其中替换 "$$"

可能的解决方案:

#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <unistd.h>

int main(void)
{
char const *input = "foo$$bar";
pid_t pid = 1234;

size_t format_length = strlen(input);
char *format = calloc(format_length + 2, 1);
if (!format) {
fputs("Couldn't allocate memory :(\n\n", stderr);
return EXIT_FAILURE;
}

// copy input to format replacing "$$" with "%ld" in the process
bool replacement_done = false;
for (size_t i = 0; i < format_length + replacement_done; ++i) {
if (!replacement_done && i + 1 < format_length &&
input[i] == '$' && input[i + 1] == '$')
{
format[ i] = '%'; // just
format[++i] = 'l'; // being
format[++i] = 'd'; // safe.
replacement_done = true;
continue;
}

format[i] = input[i - replacement_done];
}

if (!replacement_done) {
free(format);
fputs("Nothing to do :(\n\n", stderr);
return EXIT_FAILURE;
}

char *result = malloc(1);
if (!result) {
free(format);
fputs("Couldn't allocate memory :(\n\n", stderr);
return EXIT_FAILURE;
}

// there is no guesswork needed, snprintf() will tell the needed size
int bytes_needed = snprintf(result, 1, format, (long)getpid());
if (bytes_needed < 0) {
free(format);
free(result);
fputs("snprintf() failed :(\n\n", stderr);
return EXIT_FAILURE;
}

char *temp = realloc(result, ++bytes_needed);
if (!temp) {
free(format);
free(result);
fputs("Couldn't allocate memory :(\n\n", stderr);
return EXIT_FAILURE;
}
result = temp;

int written = snprintf(result, bytes_needed, format, (long)getpid()); // long should be big enough
if(written < 0 || written >= bytes_needed ) {
free(format);
free(result);
fputs("snprintf() failed :(\n\n", stderr);
return EXIT_FAILURE;
}

puts(result); // done.

free(format);
free(result);
}

关于C - 用 getpid() 中的 ID 替换字符串中的 $$?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311499/

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