>我正在尝试输入一串字符并将它们递归地分成两半,直到字符长度仅为 2。然后取 2 的 char 字符串并将其与旁边的 char 字符串交换。我的代码如下:
#include <stdio.h>
#include <string.h>
void encrypt(char *str, int size);
int main(){
char input[8192];
int length;
printf("INPUT A PHRASE: ");
fgets(input, 8192, stdin);
length = strlen(input) -1;
printf("LENGTH: %dn", length);
encrypt(input, length);
printf("ENCRYPTION: %sn", input);
return 0;
}
void encrypt(char str[], int size){
int i;
int k = size / 2;
//Encryption code here
}
一些示例输出:
Sample Input:
12345678
Sample Output:
34127856
Sample Input:
Test early and often!
Sample Output:
aeyrleT sttf!enn aod
我不会要求任何人为我做作业。只是在寻找正确方向的推动,因为我很难弄清楚如何连续拆分字符串然后交换。
OP:"我不会要求任何人为我做作业。只是在寻找朝着正确方向的推动
"
递归代码需要拆分字符串并注意长度,无论是奇数还是偶数。
void encrypt(char str[], int size){
if (size <= 2) {
// do encryption, TBD code
retrun;
}
int i;
int k = size / 2; // good step 1
char *left = ____; // what is the address of the left half? (easy)
// call encrypt of the left half
encrypt(left, ___); // what is the size of the left half? (easy)
// Now do right
char *right = ____; // what is the address of the R half?
// (hint, it begins at the left half end.)
// What is the R half length (hint: total - ???)
// now call encrypt again with R half and length
encrypt(right, ___);
}