[英]C - Replace from the most to the least common letters in string1 from string2
我正在尝试应用密码方法。 我试过做一个直方图,但我没有在 main 中做 argc argv 因为我直接从那里测试它,我只是调用./a.out:
#include <stdio.h>
#include <string.h>
void cipher(const char text[], const char table[])
{
int length = strlen(text);
int hist[26]; //histogram for each letter of the alphabet
for (int i = 0; i < 26; i++)
{
hist[i] = 0;
}
char startletter;
for (const char *temp = text; *temp != '\0'; temp++)
{
startletter = *letter;
for (const char *letter = temp; *letter != '\0'; letter++)
{
if (*letter == startletter)
{
hist[*letter - 65] += 1;
}
}
}
for (int i = 0; i < 26; i++)
{
printf("%d ", hist[i]);
}
}
output:
0 0 0 0 0 15 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 3 1 0 0
(现在应该打印出string1
中出现的字母)
这是代码:
#include <stdio.h>
#include <string.h>
void cipher(const char text[], const char table[]){
int hist[26]; //histogram for each letter of the alphabet
for (int i = 0; i < 26; i++)
hist[i] = 0;
for (const char *temp = text; *temp != '\0'; temp++)
hist[*temp-65] += 1;
for (int i = 0; i < 26; i++){
if (hist[i])
printf("%c=%d\n", 'A'+i, hist[i]);
}
}
int main(void){
const char a[] = "FXOWFFOWOFF";
const char b[] = "ABCD";
cipher(a, b);
return 0;
}
您所要做的就是删除嵌套循环。
您需要对直方图进行排序,然后根据排序后的直方图从表格中打印字母
这是代码:
#include <stdio.h>
#include <string.h>
void cipher(const char text[], const char table[])
{
int length = strlen(text);
int hist[26]; //histogram for each letter of the alphabet
for (int i = 0 ; i < 26; i ++)
{
hist[i] = 0;
}
for (const char *temp = text; *temp != '\0'; temp++)
{
hist[(int)*temp - 65]++;
}
for (int i = 0; i < 26; i++)
{
printf("%d ", hist[i]);
}
printf("\n");
// sort
int sort[26];
for (int i = 0; i < 26; ++i)
{
sort[i] = i;
}
int tempint;
for (int i = 0; i < 25; ++i)
{
for (int j = i; j < 26; ++j)
{
if (hist[sort[j]] > hist[sort[i]]) {
tempint = sort[j];
sort[j] = sort[i];
sort[i] = tempint;
}
}
}
for (int i = 0; i < strlen(table); ++i)
{
printf("%c %c\n", (char)(65 + sort[i]), table[i]);
}
return;
}
int main(void)
{
const char a[] = "FXOWFFOWOFF";
const char b[] = "ABCD";
cipher(a, b);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.