int len_str(char *str){ int count = 0; while(str[count]!='\0'){ count++; } return count; }
argc 4 argv[0] "./myprog" argv[1] "-a" argv[2] "-bc" argv[3] "junk"
void reverse_string( char s[] ) { char ch; int lo=0,hi=0; while( s[hi] != '\0' ) { hi++; } hi--; // last character before '\0' while( lo < hi ) { ch = s[lo]; // swap s[lo] and s[hi] s[lo] = s[hi]; s[hi] = ch; lo++; // lo,hi both move toward middle hi--; } }
void substr( char s[], char d[], int lo, int hi ) { int i=0, j=0; // scan to s[lo], or end of s[] while( i < lo && s[i] != '\0' ) { i++; } if( i == lo ) { // keep copying until s[hi], or end of s[] while( i <= hi && s[i] != '\0' ) { d[j++] = s[i++]; } } // finally, add the end-of-string marker d[j] = '\0'; }
char *strstr( char s[], char d[] ) { char *return_pointer = NULL; int i=0, j; while( s[i] != '\0' && return_pointer == NULL ) { j=0; // compare d[] to substring of s[] starting at i while( s[i+j] == d[j] && d[j] != '\0' ) { j++; } if( d[j] == '\0' ) { // substring found return_pointer = &s[i]; // pointer to start of substring } i++; // increment start index } // if return_pointer is still NULL, the substring was not found return( return_pointer ); }Note: Later in your studies, you might learn more sophisticated ways of implementing the
strstr()
function which
are faster, such as the
Boyer-Moore algorithm
and the
Knuth-Morris-Pratt algorithm (but these are beyond the scope of this course).