How can I compare two char arrays using recursion?
- What do "sentries" mean? - TheNorthon
- suppose numeric :) - splash58
- @TheNorthon char []) sorry) automatic replacement failed - Volodymyr Samoilenko
|
3 answers
Lovers of single-line thorny expressions is dedicated to:
bool cmp(const char* s1, const char* s2) { return *s1 == *s2 ? *s1 ? cmp(++s1, ++s2) : true : false; } PS Don't try this at home
- oneI would also cut
return *s1 == *s2 && (!*s1 ||cmp(++s1, ++s2) );. And what's wrong with that you can not repeat at home? - pavel - @pavel, the code is terrible. For such a face is beaten in a decent society, therefore the postscript. - ixSci
- @pavel nested ternarks (and generally long single-line codes) are difficult to read and understand. Well, you should not use recursion where the loop is. Although here, of course, the requirements arise from the question. - 伪位蔚蠂慰位蠀蟿
- @alexolut well, I seem to have gotten rid of the ternary. Has the code become clearer? - pavel
|
#include <iostream> bool compare(const char* s1, const char* s2){ bool res; if(*s1 && (*s1 == *s2)) res = compare(s1 + 1, s2 + 1); else res = (!*s1 && !*s2); return res; } int main(void){ char s1[] = "PASCAL"; char s2[] = "PASCAL"; if(compare(s1, s2)) std::cout << "袪邪胁薪褘." << std::endl; else std::cout << "袧械褉邪胁薪芯!" << std::endl; return 0; } |
while waiting for the answer to the wrong question, he wrote it himself)
bool is_equal(char a[],char b[]) { if (a[0] == '\0' && b[0] == '\0') { return true; } else if (a[0] != b[0]) { return false; } return is_equal(a+1,b+1); } - Cons: 1. The name of the fukntion in the style of "oil-oil", i.e. 'char_array' is redundant, i.e. it is clear from the arguments that these are arrays 2. The function is not safe, it is desirable to transfer the maximum number of characters, see _s analogs in the C-documentation - sys_dev
- thanks @sys_dev - Volodymyr Samoilenko
- onepay attention to such data type as string. It will eliminate all the problems of comparison and the invention of bicycles. - V. Rotenberh
- @ V.Rotenberh I would be happy, but a professor from the university needs just such a perversion - Volodymyr Samoilenko
|