Created
August 8, 2021 10:05
-
-
Save withs/6f668c15ed5c48afc780fc44759bdc4b to your computer and use it in GitHub Desktop.
FInd in string in C String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "iostream" | |
int find(const char* word, const char* in, const int startAt = 0, int endAt = 0) { | |
int begin; | |
int verifyCount = 0; | |
int withSize = std::strlen(in); | |
// loop jusqu'a trouver une égalité du premier characthere de word et le char de l'index dans la loop | |
for ( int i = startAt; i <= ((endAt == 0) ? withSize:endAt); i++ ) { | |
// si le premier char de word et le char de l'index dans la loop sont égaux alors ont enrefistre l'index | |
// qui correspond a la position du premier char de word | |
if ( in[i] == word[0] ) { | |
begin = i; | |
// loop en testant l'egalité de tout word par raport a begin | |
for ( int s = 0; s < std::strlen(word); s++ ) { | |
// si un char est égal alors verifyCount++ et ont test si verifyCount est égal a la taille de word | |
// si oui cela veut dire que nous avons trouvé la position de word sinon on repart pour un tour | |
if ( in[i + s] == word[s]) { | |
verifyCount++; | |
if ( verifyCount == std::strlen(word) ) | |
return begin; | |
} | |
} | |
verifyCount = 0; | |
} | |
} | |
return -1; | |
} | |
int main(int argc, char const *argv[]) { | |
const char* myText = "hello my name is zuzi !"; | |
int zuziPos = find("zuzi", myText); | |
int myPos = find("my", myText, 5); | |
int isBtwNameAndZuziPos = find("is", myText, 9, 17); | |
std::cout << "zuzi position : " << zuziPos << '\n'; | |
std::cout << "my position after the word my : " << myPos << '\n'; | |
std::cout << "is position between name ans zuzi : " << isBtwNameAndZuziPos << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment