在C字符串中添加字符填充



我正在尝试为一个数字列表实现这个简单的加密方法,加密如下:我们在整个数字列表的每个元素之前添加列表的第一个元素,如果我们有:

char array = "356307042441013"

第一个数字是3,这意味着我们需要在数字列表的每个元素之前添加它:

'33 35 36 33 30 37 30 34 32 34 34  31 30 31 33'
char result= "333536333037303432343431303133"

C中有什么函数可以使实现更容易吗?因为我试过换挡,但没能得到结果。

您可以执行以下操作:

步骤I:分配两倍于输入和+ 1大小的内存,以将空字符容纳到结果字符串中
第二步:遍历输入字符串,在每次迭代中,首先将input[0]字符复制到结果字符串的当前位置,然后在结果字符串的下一个位置复制input字符串的当前处理字符
第三步:循环退出后,在结果字符串的末尾添加null字符
[要特别注意空字符串,因为它没有什么可加密的]

实施:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * encryption (const char * input) {
if ((!input) || (*input == '')) {
return NULL;
}
size_t len = strlen (input);
char * temp = malloc ((len * 2) + 1);
if (!temp) {
printf ("Failed to allocate memoryn");
exit (EXIT_FAILURE);
}
size_t i = 0, j = 0;
for (; input[j]; ++j) {
temp[i++] = input[0];
temp[i++] = input[j];
}
temp[i] = '';
return temp;
}
int main (void) {
char array[] = "356307042441013";
char * result = encryption (array);
if (result) {
printf ("result : %sn", result);
// Free the dynamically allocated memory once done with it
free (result);
}
return 0;
}

输出:

# ./a.out
result : 333536333037303432343431303133

更清洁、更简洁的解决方案:

#include <stdio.h>
#include <string.h>
int main()
{
char foo[] = "356307042441013"; 
char bar[2 * sizeof(foo) - 1];
char *src = foo, *dest = bar;
while (*src) {
*dest++ = foo[0];
*dest++ = *src++;
}
*dest = *src;
printf("foo=%sn",foo);
printf("bar=%sn",bar);
return 0;
}

最好使用foo[],而不是对长度进行硬编码,因为如果您想更改字符串怎么办。如果使用[](空括号(,编译器将精确分配所需的字节数(包括终止的null(。类似地,对于bar,我们以foo的大小为基础,将其加倍并减去1(因为终止的null不需要加倍(。

我找到了解决这个问题的方法:

int main() {
char foo[16] = "356307042441013"; 
char bar[2*16-1];
for (int i = 0; i < 16; i++) {
bar[2*i] = foo[i];
if (i != 16 - 1)
bar[2*i + 1] = foo[0];
}
char res[32]= "3";
strcat(res,bar);
res[30] = '';
printf("bar=%srn",bar);
printf("begin=%srn",res);
return 0;
}

最新更新