[英]C Programming - How to change every occurrence of character in a string with another character
任務是讓用戶插入一個字符串,程序將 output 一條秘密消息,用另一個字符更改該字符串的每個字符的出現。 將插入的新字符列表由排列“qjczieaungsdfxmphybklortvw”給出,它對應於字母表的每個字母。 例如,字符串“abcxyz”將返回“qjctvw”。 程序將忽略符號和大寫字母,因此“Abc”將變為“Ajc”。
我試圖通過將字符串的每個 position 與字母表中的每個字母進行比較來實現這一點。 如果匹配,則字符串的 position 將替換為與傳統字母表的 position 相同的秘密排列的 position(因為它們對應)。 該代碼在技術上有效,但我沒有得到正確的值。 例如,對於每個“a”,我應該得到一個“q”,但返回的是一個“h”。 如果有人可以修復我的代碼,將不勝感激。 下面的代碼:請復制並粘貼到您喜歡的代碼編輯器中,看看我返回錯誤值的意思。
#include <string.h>
#define MAX_STR_LEN 256
int main(void)
{
char perm[] = "qjczieaungsdfxmphybklortvw";
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
int i, j;
char msg[MAX_STR_LEN+1];
/* read the message from the terminal using fgets. The variable msg will contain the message. */
fgets(msg, MAX_STR_LEN, stdin);
/*compares each value of the string to the alphabet*/
for (i = 0; i < (strlen(msg) - 1); i++) {
for (j = 0; j < (strlen(alphabet) - 1); j++) {
if (msg[i] == alphabet[j]) {msg[i] = perm[j];}
}
}
printf("%s", msg);
}
對於調用 fgets 后的初學者
fgets(msg, MAX_STR_LEN, stdin);
您需要刪除 function 可以附加到輸入字符串的換行符。
msg[ strcspn( msg, "\n" ) ] = '\0';
for 循環也不正確。 您可以使用 function strchr
。 例如
/*compares each value of the string to the alphabet*/
for ( size_t i = 0; msg[i] != '\0'; i++ )
{
const char *p = strchr( alphabet, msg[i] );
if ( p != NULL )
{
msg[i] = perm[p - alphabet];
}
}
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#define MAX_STR_LEN 256
int main(void)
{
char perm[] = "qjczieaungsdfxmphybklortvw";
char msg[MAX_STR_LEN+1];
/* read the message from the terminal using fgets. The variable msg will contain the message. */
fgets(msg, MAX_STR_LEN, stdin);
for (unsigned short i = 0; i < strlen(msg) - 1; ++i)
if (islower(msg[i]))
msg[i] = perm[i];
printf("%s", msg);
return 0;
}
嘗試這個
一旦您找到問題的根源並觀察到:
('b'=='a'+1)
。 有了這些知識,我們可以發明一個 function,它接受一個字符並將其轉換為perm
字符串中正確的 position。 我們可以通過非常簡單的方式做到這一點,只需從我們擁有的任何字符中減去'a'
。 'a'-'a'
將等於 0,依此類推。
這可以像這樣實現為 function :(或者你可以內聯它,因為它很簡單)
int get_char_index(char c){
return c - 'a';
}
現在,可以訪問這個 function,我們需要做的就是逐個字符地迭代字符串(for 循環,while 循環,沒關系),從字符串中讀取字符,將其提供給 function,然后然后,一旦您獲得perm
的相應索引,您只需將該索引下的 char 的值分配回字符串。
int main() {
const char perm[] = "qjczieaungsdfxmphybklortvw";
char some_string_to_convert[] = "aabbccddeeffgghhiijjkkllmmnnoopprrssttqqvvwhatever";
for(int i=0; i<strlen(some_string_to_convert); i++){
char c = some_string_to_convert[i];
int perm_index = get_char_index(c);
some_string_to_convert[i] = perm[perm_index];
}
printf("%s", some_string_to_convert);
}
以下代碼輸出: qqjjcczziieeaauunnggssddffxxmmppyybbkkhhooruqkioiy
希望我的回答能幫助你解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.