我決定執行codewars.com中的任務,該任務名為 "檢測泛語法"(泛語法是一個至少包含每個字母的句子。例如,"快速的棕色狐貍跳過懶惰的狗 "這個句子就是一個泛語法,因為它至少使用了一次字母A-Z(大小寫不相干)。 給定一個字串,檢測它是否是一個pangram。如果是,回傳True,如果不是,回傳False。忽略數字和標點符號。)。 所以我寫了這段代碼:
main.c#include <stdio.h>/span>
#include <stdlib.h>
int is_pangram(char *str)
{
int j = 0; //開始計算字串中的字符數。
while (str[j])
{
j ;
} // end count
for (int i = 0; i < j; i ) //檢查這個字串中所有字符的大寫字母。
{
if (str[i] >= 65 && str[i] <= 90) //如果這個字符是一個大寫字母(在ASCII中從65到90),。
//我們將其設定為低位字母。
{
str[i] = (int)str[i] 32;
}
}
char alphabet[26]; //創建一個空陣列。
int count_add_to_alph = 0; //設定一個成功設定字母到陣列的計數器
int counter_char = 0; //設定字符陣列的計數器。
while (str[counter_char]) //開始檢查每個字符。
{
if (str[counter_char] >= 'a' && str[counter_char] <= 'z' & & str[counter_char] ! = alphabet[str[counter_char] - 'a'] )
{ //if the number of ASCII of the character is a low letter //如果這個字母在字母表中沒有設定,我們就設定這個字母。
//進入一個陣列alphabet。
alphabet[str[counter_char] - 'a] = str[counter_char]。
count_add_to_alph ;
}
counter_char ;
} //結束檢查。
for (int i = 0; i < 26; i ) //將每個字符設為0。
{
alphabet[i] = 0;
}
if (count_add_to_alph == 26) // if all letters of english alphabet were added to the alphabet array,/span>
//我們回傳true,否則false。
{
return count_add_to_alph;
}
else 回傳 count_add_to_alph; }
{
return 0;
}
}
我開始在codewars中測驗,它回傳給我的是:
error
<錯誤
測驗結果。
例子_測驗
should_pass_all_the_tests_provided
測驗崩潰了
捕捉到意外信號。SIGSEGV(11)。無效的記憶體訪問。
在0.0000ms完成。
uj5u.com熱心網友回復:
你正在修改輸入字串。這是 "好的",但很危險。如果使用字串常量進行呼叫,它將會發生故障[因為作業系統/實作可能會將常量放入只讀記憶體]:
is_pangram("敏捷的棕色狐貍跳過懶惰的狗")。
這段代碼是很好的注釋。
但是,不要做只是模仿代碼的注釋。好的注釋應該顯示意圖。
就個人而言,我盡量避免做 "側邊欄 "評論。也就是說,我更喜歡 "整行 "的評論,在行的上方,以保持行長在 80 個字符以下。
該演算法[方式]過于復雜。因此,也更容易出錯。 不需要掃描行內的注釋。
不需要掃描字串以獲得長度,然后使用長度停止掃描的另一個回圈。更好的做法是使用指標遍歷字串,并在當前字符為 0 時停止掃描[你在第一個回圈中就是這么做的]。
不要使用 "硬接線 "的十進制常量而不是字符字面(例如)你使用 你正在使用四個回圈。整個函式可以通過一個回圈來完成資料的單一傳遞。
我不得不對代碼進行大幅度的重構。下面是注釋過的代碼:
標籤: 上一篇:在C/C 宏定義的開頭粘貼標記
下一篇:c語言的階乘程式
65而不是'A',等等。
#include <stdio.h>/span>
#include <stdlib.h>
int
is_pangram(const char *str)
{
//看到的字串列。
char already_seen[26] = { 0 };
//看到的_獨特的字符數量。
int count_add_to_alph = 0;
//loop through all input string chars.
for (int chr = *str ; chr !=0; chr = *str ) {
int idx = -1;
//如果char是alpha,得到 "alphabet "陣列的索引。
// 注意:使用(例如)isalpha/islower/isupper可能會更好,。
//等,但你在原代碼中使用了char范圍,所以我會繼續。
// that
do {
//小寫字母 do {
if ((chr >= 'a') && (chr <= 'z') ) {
idx = chr - 'a';
break。
}
//大寫字母; break; }
if ((chr >= 'A') && (chr <= 'Z') {
idx = chr - 'A';
break。
}
} while(0)。
//非alpha字符 -- 忽略。
if (idx < 0)
繼續。
//增加_unique_ alpha計數。
// NOTES:
//(1) (! foo)總是正好是0或1。
// (2) 因此,(! already_seen[idx]在第一次回傳1,然后回傳0。
//此后。
count_add_to_alph = (! already_seen[idx])。
///將alpha字符標記為已見(即不再唯一)。
already_seen[idx] = 1;
}
//我們必須看到所有26個字母。
return (count_add_to_alph == 26)。
}
