Живой образец обоих упражнений
Для Упражнение 1 , я считаю, что цель состоит в том, чтобы сделать функцию, аналогичную strcmp()
так что важен не размер, а лексикографический порядок, поэтому вам нужно сравнить каждый символ, например, cmp("abcd", "abce")
должно быть -1
, а cmp("abce", "abcd")
или cmp("abe", "ab")
должно быть 1
:
int cmp(const char* string1, const char* string2) {
do{
if(*string1 > *string2){ //because of ASCII codes you can compare characters like this
return 1;
}
if(*string1 < *string2){
return -1;
}
} while(*string1++ && *string2++); //while none of the chars is null
return 0; //reached if no different chars were found so the strings are equal
}
Для Упражнения 2 вы можете извлечь цифры в другой контейнер, отсортировать и сравнить их:
int function2 (const char * str){
vector<int> digits; //dynamic container since the digit count is unknown at first
int count = 0;
for(size_t i = 0; i < strlen(str); i++) //extract digits from string
if(str[i] >= '0' && str[i] <= '9')
digits.push_back(str[i] - '0'); //add to digit container
sort(digits.begin(), digits.end()); //sort digit vector
for(size_t i = 0; i < digits.size() - 1; i++){ //compare digits and count if no repeat
if(digits[i] != digits[i + 1] && digits[i + 1] != digits[i + 2]){
count++;
}
}
return count;
}
Библиотеки
#include <cstring>
#include <vector>
#include <algorithm>