C语言字符串填充问题?

老师们好:

C 语言实现, 给定一个字符串长度不是16字节倍数时,请将字符串左边用0填充,使其长度为16字节的整倍数。
期望得到下面给出的结果

例1: char arr[] ="12345678"; 程序运行结果, char arr1[]="0000000012345678";
例2: char arr3[] ="123456789123456789"; 程序运行结果, char arr4[]="00000000000000123456789123456789";
例2: char arr5[] ="123456789012345678901234567890123"; 程序运行结果, char arr6[]="000000000000000123456789012345678901234567890123";
......
阅读 2.9k
1 个回答
✓ 已被采纳

思路:将长度除以16然后向上取整(注意数据类型),然后取整前后的差为填充长度。
实现:

void padStringWithZeros(char *input) {
    int inputLength = strlen(input);
    int targetLength = ((inputLength - 1) / 16 + 1) * 16;  // 向上取整
    
    int zerosToAdd = targetLength - inputLength;
    
    // Shift the existing characters to the right to make space for the zeros
    memmove(input + zerosToAdd, input, inputLength + 1);
    
    // Fill the beginning with zeros
    for (int i = 0; i < zerosToAdd; ++i) {
        input[i] = '0';
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进