我正在嘗試創建一個函式,該函式將字串作為輸入并將每個字符相互比較以確保它們不會重復。
該字串由 26 個字母字符組成 目標是相互比較 26 個字符以確保沒有重復。為此,我想使用strcmp(因為我不知道任何比較字符的函式)。
為此,我首先需要將代碼中的字符轉換為字串以便比較它們。我該怎么做呢?
這是我的功能:
bool is_valid_key(string verify)
int a = 0;
int b = 0;
string s1 = verify[a], s2 = verify[b];
for ( a = 0; a < verify[a]; a )
{
if (strcmp( s1, s2) == 0)
return 0;
}
return 1;
uj5u.com熱心網友回復:
您不需要比較此測驗的字串,只需比較單個char值。char可以比較值==,!=因此您可以撰寫 2 個嵌套回圈:
bool is_valid_key(const char *key) {
for (int a = 0; key[a] != '\0'; a ) {
for (int b = 0; b < a; b ) {
// if 2 characters match, the key is not valid
if (key[a] == key[b])
return false;
}
}
// all characters are different: key is valid
return true;
}
這種方法的問題是您不測驗密鑰長度,也不是它僅由字母組成。
這是一種不同的方法:
// check that key contains 26 lowercase letters without duplicates
bool is_valid_key(const char *key) {
unsigned long mask = 0;
for (int i = 0; key[i] != '\0'; i ) {
if (key[i] < 'a' || key[i] > 'z') {
// invalid character
return false;
}
// this assumes that letters are contiguous, which is true for ASCII
unsigned long bit = 1UL << (key[i] - 'a');
if (mask & bit) {
// duplicate character
return false;
}
mask |= bit;
}
// check that all 26 letters have been set
return mask == (1UL << 27) - 1;
}
uj5u.com熱心網友回復:
這些宣告和以下 for 回圈
string s1 = verify[a], s2 = verify[b];
for ( a = 0; a < verify[a]; a )
//...
沒有意義。
例如,宣告的s1和s2具有指標型別string( char *),而初始化的運算式具有型別char。
玩具需要比較人物。
該功能可以如下所示
bool is_valid_key( string verify )
{
bool unique = true;
for ( ; unique && *verify != '\0'; verify )
{
string next = verify 1;
while ( *next != '\0' && *next != *verify ) next;
unique = *next == '\0';
}
return unique;
}
如果您需要檢查字串的所有元素是否都是字母符號,那么您可以撰寫
#include <ctype.h>
//...
bool is_valid_key( string verify )
{
bool valid = true;
for ( ; valid && *verify != '\0'; verify )
{
if ( ( valid = isalpha( ( unsigned char )*verify ) ) )
{
string next = verify 1;
while ( isupper( ( unsigned char )*next ) && *next != *verify ) next;
valid = *next == '\0';
}
}
return valid;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/516693.html
上一篇:結構值無法輸入文本
