眼前的问题
The strcspn()
函数接受两个字符串作为参数,但您传递的是一个字符串和一个字符。您需要以某种方式将字符转换为字符串。一种方法是:
int sep[2] = "";
sep[0] = letter2;
string[strcspn(string, sep)] = letter3;
sep[0] = letter3;
string[strcspn(string, sep)] = letter2;
但是,第一次调用会更改第一次出现的位置letter2
to letter3
;第二次调用改变了第一次出现的letter3
(这可能是在上一次调用中刚刚替换的)letter2
。这不是一个完整的字符串转换工作——您需要扫描整个字符串来进行更改。
实施解决方案
一种可能性是这样的:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define NULL_VALUE '\0'
static inline void map(char *str, int len, int c_old, int c_new)
{
for (int i = 0; i < len; i++)
{
if (str[i] == c_old)
str[i] = c_new;
}
}
int main(void)
{
char buffer[4096];
printf("Enter a sentence: ");
if (fgets(buffer, sizeof(buffer), stdin) == 0)
return 0;
int length = strlen(buffer);
if (length > 0)
buffer[--length] = '\0';
putchar('\n');
printf("Original [%s]\n", buffer);
int count[256] = { 0 };
for (int i = 0; i < length; i++)
{
if (isalpha((unsigned char)buffer[i]))
count[(unsigned char)buffer[i]]++;
}
int max1_count = 0;
int max2_count = 0;
char max1_value = '\0';
char max2_value = '\0';
for (int i = 0; i < 256; i++)
{
if (count[i] > max1_count)
{
max2_count = max1_count;
max2_value = max1_value;
max1_count = count[i];
max1_value = i;
}
else if (count[i] > max2_count)
{
max2_count = count[i];
max2_value = i;
}
}
/*
** Since a string is a sequence of non-null character codes followed
** by a null byte, it is safe to use '\0' as the temporary value in
** the three-step swap operation
*/
if (max2_count > 0)
{
map(buffer, length, max1_value, NULL_VALUE);
map(buffer, length, max2_value, max1_value);
map(buffer, length, NULL_VALUE, max2_value);
}
printf("Revised [%s]\n", buffer);
return 0;
}
使用宏的唯一原因NULL_VALUE
使得三者对称map()
线条是不言而喻的。
运行示例
我调用了该程序ccswap19
,我使用 Bash 'here strings' 来提供数据 —putchar('\n');
意味着输出出现在与提示不同的行上。如果您以交互方式运行该程序,则在“原始”打印之前会有一个空行。
$ ccswap19 <<< "The hidden costs of the exodus are now revealed for all to see."
Enter a sentence:
Original [The hidden costs of the exodus are now revealed for all to see.]
Revised [Tho hiddon cests ef tho oxedus aro new rovoalod fer all te soo.]
$ ccswap19 <<< "aaaaaaaaaaaa"
Enter a sentence:
Original [aaaaaaaaaaaa]
Revised [aaaaaaaaaaaa]
$ ccswap19 <<< "aaaabaaaaaaa"
Enter a sentence:
Original [aaaabaaaaaaa]
Revised [bbbbabbbbbbb]
$