gpt4 book ai didi

C - 使用 sprintf() 在字符串中添加前缀

转载 作者:行者123 更新时间:2023-11-30 14:37:59 29 4
gpt4 key购买 nike

我正在尝试使用 sprintf() 将字符串“放入其自身内部”,因此我可以将其更改为具有整数前缀。我正在长度为 12 的字符数组上进行测试,其中已经包含“Hello World”。

基本前提是我想要一个表示字符串中单词数量的前缀。所以我将 11 个字符复制到长度为 12 的字符数组中。然后我尝试在函数中使用 "%i%s" 将整数后跟字符串本身。为了超过整数(我不只是使用 myStr 作为 %s 的参数),我确保使用 myStr + snprintf(NULL, 0, "%i", wordCount ),应该是 myStr + 整数所占的字符。

问题是我遇到的问题是,当我这样做时,它会吃掉“H”并打印“2ello World”,而不是在“Hello World”旁边显示“2”

到目前为止,当我尝试将字符串复制到其自身内部时,我已经尝试了不同的选项来获取字符串中的“过去的整数”,但似乎没有什么真正是正确的情况,因为它要么以空字符串的形式出现,要么以空字符串的形式出现。只是将整数前缀“222222222222”复制到整个数组中。

int main() {
char myStr[12];
strcpy(myStr, "Hello World");//11 Characters in length
int wordCount = 2;

//Put the integer wordCount followed by the string myStr (past whatever amount of characters the integer would take up) inside of myStr
sprintf(myStr, "%i%s", wordCount, myStr + snprintf(NULL, 0, "%i", wordCount));
printf("\nChanged myStr '%s'\n", myStr);//Prints '2ello World'
return 0;
}

最佳答案

首先,要在字符串“Hello World”中插入一位数字前缀,您需要一个 13 个字符的缓冲区 - 一个用于前缀,十一个用于“Hello World”中的字符,一个用于终止空字符.

其次,您不应将缓冲区同时作为输出缓冲区和输入字符串传递给 snprintf。当传递给它的对象重叠时,它的行为不是由 C 标准定义的。

下面的程序向您展示了如何通过使用 memmove 移动字符串来插入前缀。这主要是教程,因为它通常不是操作字符串的好方法。对于短字符串,空间不是问题,大多数程序员只需将所需的字符串打印到临时缓冲区中,以避免重叠问题。

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


/* Insert a decimal numeral for Prefix into the beginning of String.
Length specifies the total number of bytes available at String.
*/
static void InsertPrefix(char *String, size_t Length, int Prefix)
{
// Find out how many characters the numeral needs.
int CharactersNeeded = snprintf(NULL, 0, "%i", Prefix);

// Find the current string length.
size_t Current = strlen(String);

/* Test whether there is enough space for the prefix, the current string,
and the terminating null character.
*/
if (Length < CharactersNeeded + Current + 1)
{
fprintf(stderr,
"Error, not enough space in string to insert prefix.\n");
exit(EXIT_FAILURE);
}

// Move the string to make room for the prefix.
memmove(String + CharactersNeeded, String, Current + 1);

/* Remember the first character, because snprintf will overwrite it with a
null character.
*/
char Temporary = String[0];

// Write the prefix, including a terminating null character.
snprintf(String, CharactersNeeded + 1, "%i", Prefix);

// Restore the first character of the original string.
String[CharactersNeeded] = Temporary;
}

int main(void)
{
char MyString[13] = "Hello World";

InsertPrefix(MyString, sizeof MyString, 2);

printf("Result = \"%s\".\n", MyString);
}

关于C - 使用 sprintf() 在字符串中添加前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917224/

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