Code: Show/Hide Player* FindPlayerByName(char *name, bool exactmatch, _linkedlist <Player>* list); int FirstDifferentCharacter(char *string1, char *string2); Player* FindPlayerByName(char *name, bool exactmatch, _linkedlist <Player>* list) { _listnode <Player> *parse = list->head; //set to first link of the player linked list Player* bestmatchplayer = NULL; int bestmatchlength = 0; String nametofind = name; nametofind.lcase(); while (parse) //parse will be NULL when we reach the last link { Player *p = parse->item; //item is the actual data stored in the link String pname = (String) p->name; pname.lcase(); if (pname == nametofind) return p; if (!exactmatch) { int firstdifferent = FirstDifferentCharacter(nametofind, pname); if (bestmatchlength < firstdifferent) { bestmatchlength = firstdifferent; bestmatchplayer = p; } } parse = parse->next; //set parse to the next link } return bestmatchplayer; } //Zero-based index of the first different character in both string. //If both strings are the same, will return the length of the string. int FirstDifferentCharacter(char *string1, char *string2) { int i; for (i = 0 ; string1[i] != '\0' && string2[i] != '\0' && tolower(string1[i]) == tolower(string2[i]) ; i++) { } return i; } |
Code: Show/Hide int FirstDifferentCharacter(const char *string1, const char *string2)
{ int i; for (i = 0 ; *string1 != '\0' && *string2 != '\0' && tolower(*string1) == tolower(*string2) ; i++, string1++, string2++) { } return i; } |
Cyan~Fire wrote: | |
Hey Samapico, here's some faster code:
Runs faster (or maybe the same after the compiler has optimized it). Just a hint for future iterative algorithms you write. ![]() |
Code: Show/Hide Player* FindPlayerByName(const char *startsWith, _linkedlist <Player>* list)
{ Player* rv = NULL; int len = (int)strlen(startsWith); for (_listnode <Player> *parse = list->head; parse; parse = parse->next) { Player* p = parse->item; if (strnicmp(p->name,startsWith,len) == 0) { rv = p; if (stricmp(p->name,startsWith) == 0) break; } } return rv; } |