c - 在某些字符串中填充前导零(0 个字符)

标签 c

如果字符串(包含数字)的内容小于字符串的大小,我必须用前导零填充该字符串。

示例:

char str[11] = "12345";

预期输出应为:0000012345

我使用 sprintf 填充了前导 0string,但使用 整数 作为参数:

sprintf(out_str,"%010d",some_integer);  //out_str is a string of 11 characters

但现在我只剩下两种方法来用前导零填充字符串(包含数字):

第一种方法

char main_string[11] = "12345";
char temp_string[11] = "";

sprintf("temp_string,"%010d", atoi(main_string));

strcpy(main_string,temp_string);

第二种方法

char main_string[11] = "12345";
char temp_string[11] = "";

memset(temp_string,'0',sizeof(temp_string));

strcpy(temp_string + sizeof(temp_string) - 1 - strlen(main_string), main_string);

strcpy(main_string, temp_string);

如果我尝试使用 sprintfstring 作为参数,我会得到前导空白:

char main_string[11] = "12345";
char temp_string[11] = "";


sprintf(temp_string,"%010s",main_string);
printf("%s",temp_string);

输出:

     12345   //leading spaces

有什么简单的方法可以实现这一点吗?

最佳答案

假设你想要原数组中填充的字符串,可以使用memmove将数字移至数组末尾,然后使用memset填充带零。

char str[11] = "12345";
size_t text_size = strlen(str) + 1;
memmove(str + sizeof(str) - text_size, str, text_size);
memset(str, '0', sizeof(str) - text_size);

关于c - 在某些字符串中填充前导零(0 个字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60236130/

相关文章:

c - 设置 tcp header 中的最大段大小

c - 如果我只有设备缓冲区 (PCIe) 的物理地址,我该如何将此缓冲区映射到用户空间?

c - C 编程语言 (K&R) - 练习 1-13

c - 套接字编程,ipv6客户端程序不工作

用ASM编译ASM和C调试

c - gtk 应用程序中的多任务

c - local_fiq_enable() 的功能

c - 创建指向最初由 malloc 创建的区域的新指针时,我是否应该调用 free

c - 按其中一个字符串值的字母顺序对结构数组进行排序的函数

c - 将字符串中的字符串替换为字符