【问题标题】:How to convert every letter of a string to another letter? in C如何将字符串的每个字母转换为另一个字母?在 C 中
【发布时间】:2021-03-17 07:50:39
【问题描述】:

这是我的第一篇文章,如果格式不合适,请告诉我。谢谢。 我目前正在尝试设计一种算法来做这样的事情:

它要求不同的字母组成一个n位数的字符串,然后它要求一个密钥字母'cypher key',然后它转换字符串的每个字母加上密钥字母,例如:

How many characters? 3  
Next character (1/3)? h  
Next character (2/3)? a  
Next character (3/3)? l  
-> [ h a l ]  
Caesar cypher key? b  
Encrypting...  
-> [ i b m ]  

这里我留下另一个代码应该做什么的例子:

How many characters? 3  
Next character (1/3)? z  
Next character (2/3)? h  
Next character (3/3)? h  
-> [ z h h ]  
Caesar cypher key? a  
Encrypting...  
-> [ z h h ]  

在本例中,如 a=0,字母将是相同的

你可以看到它要求输入一定数量的字符,这将是字符串的大小,然后你可以输入数字,然后它打印数字,然后它要求输入密钥字母,它“加密”字符串,然后它显示相同的字符串,但将键字母的值添加到字符串的每个字母中。

显然必须使用 ASCII 表。

我不太擅长使用字符串和函数,所以可能会导致一些错误。

这里我把代码和 cmets (//...) 一起留给你看:

#include <stdio.h>
#include <string.h>
#define SIZE 20

//argument with no return value function to change the value of str1 with the 'cypher key'.
void moveLetters (char str1[], char cypher_key) {

    int i;  
    int len;
    
    len = strlen(str1);
    
    //loop to convert every character of the string with the cypher key value
    for (i = 0; i < len; i++) {
        
        str1[i] = (str1[i] + cypher_key - 97 * 2) % 26 + 97;
    }
}



int main () {
    
    int n_characters;
    char str1[SIZE];
    char cypher_key;
    int i;
    int t = 0;
    
    //asks for the amount of values of the string which can't be less than 0.
    do {
    
        printf ("How many characters? ");
        scanf ("%d", &n_characters);
        
    } while (n_characters <= 0);
    
    //asks for every character depending on the amount.
    for (i = n_characters; i > 0; i--) {
        
        printf ("Next character (%d/%d)? ", t + 1, n_characters);   
        scanf ("%s", &str1[t]);
        
        t++;
                
    }
    
    printf ("-> [%s]\n", str1);
        
    printf ("Caesar cypher key? ");
    scanf ("%s", &cypher_key);
    
    //here I have my doubts because i don't really know if this is a correct way to send a value to a 
    //function and return it to the main
    moveLetters (str1, cypher_key);
    
    printf ("Encrypting...\n");
    
    printf ("-> [%s]", str1);
    
    
    return 0;
}

会发生什么,由于某种原因,它在最后一个 printf 中什么也没打印,所以我不明白 void 函数或其他地方发生了什么。

【问题讨论】:

    标签: c string function arguments character


    【解决方案1】:

    最后一个 printf 有效。完全没有问题。换一个新行,让你看得更清楚。

    printf ("-> [%s]\n", str1);
    

    【讨论】:

    • 嗨,Yoan,感谢您的评论。你能把你的代码发给我看看我到底在哪里犯了错误,因为它在最后一个 printf 中什么也没打印。谢谢!!!!
    • @Sergi212 我的代码和你的一样。也许问题出在你的机器上。你如何编译和运行你的代码?
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多